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对象并显示。
    • 运行应用程序事件循环。
相关推荐
QQ_4376643143 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
liulilittle5 小时前
C++/CLI与标准C++的语法差异(一)
开发语言·c++·.net·cli·clr·托管·原生
小狄同学呀5 小时前
VS插件报错,g++却完美编译?API调用错因分析
c++
程序员编程指南5 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
小乖兽技术5 小时前
C#与C++交互开发系列(二十四):WinForms 应用中嵌入C++ 原生窗体
c++·c#·交互
张北北.5 小时前
【深入底层】C++开发简历4+4技能描述6
java·开发语言·c++
晨风先生6 小时前
如何Visual Studio 的配置从 Qt-Debug 切换到 x64-Debug
ide·qt·visual studio
刚入坑的新人编程6 小时前
暑期算法训练.9
数据结构·c++·算法·leetcode·面试·排序算法
破刺不会编程8 小时前
linux线程概念和控制
linux·运维·服务器·开发语言·c++
程序员编程指南8 小时前
Qt OpenGL 集成:开发 3D 图形应用
c语言·数据库·c++·qt·3d