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 分钟前
C++高并发内存池:内存池调优与测试
c++·后端·哈希算法·visual studio
雾隐潇湘13 分钟前
C++——第三篇 继承与多态
开发语言·c++
阿贵---15 分钟前
分布式系统C++实现
开发语言·c++·算法
不染尘.16 分钟前
最短路径之Bellman-Ford算法
开发语言·数据结构·c++·算法·图论
Reisentyan16 分钟前
[Refactor]CPP Learn Data Day 1
c++·重构
xiaoye-duck18 分钟前
C++ STL set 系列深度解析:从底层原理、核心接口到实战场景
开发语言·c++·stl
m0_6625779721 分钟前
C++中的RAII技术深入
开发语言·c++·算法
旖-旎21 分钟前
二分查找(点名)(8)
c++·算法·二分查找·力扣
承渊政道24 分钟前
【优选算法】(实战体验滑动窗口的奇妙之旅)
c语言·c++·笔记·学习·算法·leetcode·visual studio
2401_8914821737 分钟前
C++代码复杂性分析
开发语言·c++·算法