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】QPixmap QImage QBitmap QPicture
开发语言·c++·qt
攻城狮7号12 分钟前
【第39节】windows编程:打造MFC版本任务管理器
c++·windows·mfc·任务管理器
落笔映浮华丶1 小时前
C++(进阶) 第11智能指针
开发语言·c++
ephemerals__1 小时前
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
开发语言·c++
weixin_445054721 小时前
力扣刷题-热题100题-第34题(c++、python)
c++·python·leetcode
姜行运1 小时前
C++【string类】(一)
android·开发语言·c++
一只码代码的章鱼1 小时前
数据结构与算法-图论-复习1(单源最短路,全源最短路,最小生成树)
c++·算法·图论
什码情况1 小时前
整数编码 - 华为OD统一考试(A卷、C++)
数据结构·c++·算法·华为od
martian6651 小时前
C++面向对象编程优化实战:破解性能瓶颈,提升应用效率
开发语言·c++·性能优化
Zhichao_972 小时前
【UE5 C++课程系列笔记】34——结构体与Json的相互转化
c++·笔记·ue5