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对象并显示。
    • 运行应用程序事件循环。
相关推荐
谱写秋天6 分钟前
Qt 5.5 的安装与配置(使用 VSCode编辑)
开发语言·vscode·qt
快乐的划水a9 小时前
组合模式及优化
c++·设计模式·组合模式
星星火柴93610 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑11 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
阿巴~阿巴~13 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
旺小仔.14 小时前
双指针和codetop复习
数据结构·c++·算法
jingfeng51414 小时前
C++ STL-string类底层实现
前端·c++·算法
郝学胜-神的一滴14 小时前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl
前端市界15 小时前
前端视角: PyQt6+Vue3 跨界开发实战
前端·qt·pyqt
努力努力再努力wz16 小时前
【c++深入系列】:万字详解模版(下)
java·c++·redis