Qt:QtFileDialog打开文件选择对话框选择文件

在Qt中,你可以使用QFileDialog类来打开文件选择对话框,让用户选择文件。以下是一个简单的示例,演示如何使用QFileDialog打开文件选择对话框并获取用户选择的文件路径。

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QLabel>

class FileDialogExample : public QWidget {
    Q_OBJECT

public:
    FileDialogExample(QWidget *parent = nullptr);

private slots:
    void openFileDialog();

private:
    QLabel *label;
};

FileDialogExample::FileDialogExample(QWidget *parent)
    : QWidget(parent), label(new QLabel(this)) {
    QPushButton *button = new QPushButton("Open File", this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(button);
    layout->addWidget(label);

    connect(button, &QPushButton::clicked, this, &FileDialogExample::openFileDialog);

    setLayout(layout);
    setWindowTitle("File Dialog Example");
    resize(300, 200);
}

void FileDialogExample::openFileDialog() {
    QString fileName = QFileDialog::getOpenFileName(this, "Open File", "", "All Files (*);;Text Files (*.txt)");
//tr("images(*.png *jpeg *bmp);;video files(*.avi *.mp4 *.wmv);;All files(*.*)"))
    if (!fileName.isEmpty()) {
        label->setText(fileName);
    } else {
        label->setText("No file selected");
    }
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    FileDialogExample example;
    example.show();
    return app.exec();
}

  • 创建主窗口类FileDialogExample

    • 继承自QWidget
    • 定义一个构造函数来初始化UI组件。
    • 定义一个槽函数openFileDialog()来打开文件选择对话框。
  • 在构造函数中设置UI组件

    • 创建一个按钮和标签,并将它们添加到垂直布局中。
    • 连接按钮的点击信号到槽函数openFileDialog()
    • 设置窗口的标题和大小。
  • 实现openFileDialog()槽函数

    • 使用QFileDialog::getOpenFileName()打开文件选择对话框。
    • 如果用户选择了文件,显示文件路径;否则,显示"没有选择文件"。
  • 主函数

    • 创建QApplication对象。
    • 创建FileDialogExample对象并显示。
    • 运行应用程序事件循环。

相关推荐

  1. Qt:QtFileDialog打开文件选择对话框选择文件

    2024-06-07 23:58:04       10 阅读
  2. MATLAB 打开文件对话框选择点云输入 (52)

    2024-06-07 23:58:04       15 阅读
  3. python界面开发 - filedialog 文件选择对话框

    2024-06-07 23:58:04       21 阅读
  4. perl:打开文件夹选择视频文件,并播放

    2024-06-07 23:58:04       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-07 23:58:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-07 23:58:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-07 23:58:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-07 23:58:04       18 阅读

热门阅读

  1. MATLAB .m文件的命名规则

    2024-06-07 23:58:04       6 阅读
  2. C#语言进阶(三) 元组

    2024-06-07 23:58:04       5 阅读
  3. 备份Docker部署的MySQL

    2024-06-07 23:58:04       7 阅读
  4. python 批量ts合并成一个mp4

    2024-06-07 23:58:04       8 阅读
  5. .NET与C#和PLC交互的例子

    2024-06-07 23:58:04       6 阅读
  6. 云服务器与虚拟服务器的区别

    2024-06-07 23:58:04       8 阅读
  7. 设计模式之单例模式

    2024-06-07 23:58:04       9 阅读
  8. 大模型日报2024-06-07

    2024-06-07 23:58:04       8 阅读
  9. 【机器学习】原理与应用场景 Python代码展现

    2024-06-07 23:58:04       9 阅读
  10. stream流的常见使用

    2024-06-07 23:58:04       7 阅读