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对象并显示。
    • 运行应用程序事件循环。
相关推荐
derek19971 小时前
软考软件设计师:主键、传递依赖和冗余,三问其实是一件事
c语言·c++·计算机网络·软件工程·学习方法
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】解决Unicode码转化以及界面变形问题
前端·c++·人工智能·学习·安全·架构
ShineWinsu2 小时前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
悠仁さん4 小时前
【C++】unordered_map_set 模拟实现
开发语言·c++
kissskill6 小时前
MUDUO 学习笔记
c++·muduo
ShineWinsu19 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
闻缺陷则喜何志丹21 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain1 天前
某游戏公司C++游开实习 机试复盘
c++·游戏
炸膛坦客1 天前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长1 天前
C++:C++11特性
开发语言·c++·算法