使用getExistingDirectory()选择已存在的文件夹
发布时间:2023-12-22 23:01:26
getExistingDirectory()是一个Qt中的函数,用于打开一个文件夹选择对话框,让用户选择一个已经存在的文件夹。该函数返回用户选择的文件夹的路径。
下面是一个使用getExistingDirectory()的例子:
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建一个按钮,点击按钮后弹出文件夹选择对话框
QPushButton button("选择文件夹");
QObject::connect(&button, &QPushButton::clicked, [&](){
QString folderPath = QFileDialog::getExistingDirectory(nullptr, "选择文件夹", ".", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!folderPath.isEmpty()){
qDebug() << "选择的文件夹路径:" << folderPath;
}
});
// 创建一个布局,将按钮添加到布局中
QVBoxLayout layout;
layout.addWidget(&button);
// 创建一个窗口,设置布局
QWidget window;
window.setLayout(&layout);
window.show();
return app.exec();
}
在上面的例子中,首先创建一个QPushButton,当按钮被点击时,调用getExistingDirectory()函数打开一个文件夹选择对话框,并传入参数来指定只显示文件夹选项,并且不解析符号链接。用户选择的文件夹路径将通过信号传递给槽函数,然后在槽函数中将路径打印出来。
然后,使用QVBoxLayout来创建一个垂直布局,并将按钮添加到布局中。
最后,创建一个Qwidget窗口,并将布局设置给窗口,最后显示窗口。
当运行该程序时,点击按钮后会弹出一个文件夹选择对话框,用户可以选择一个已经存在的文件夹,然后选择的文件夹路径将会被打印出来。
这就是使用getExistingDirectory()函数选择已存在的文件夹的一个例子。
