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对象并显示。
    • 运行应用程序事件循环。
相关推荐
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
我真不会起名字啊3 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg3 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
牵牛老人3 小时前
Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件
数据库·qt·pdf
水瓶丫头站住3 小时前
Qt的QStackedWidget样式设置
开发语言·qt
ox00805 小时前
C++ 设计模式-命令模式
c++·设计模式·命令模式
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit6 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
..过云雨6 小时前
04.类和对象(下)(初始化列表、static静态成员、友元friend[类外函数使用类私有成员]、内部类、匿名对象等)
开发语言·c++
刃神太酷啦6 小时前
树(数据结构·)
数据结构·c++·蓝桥杯c++组