1. QT文档中说明,正常是不提供同时选择目录和文件夹功能的
The QFileDialog class enables a user to traverse the file system in order to select one or many files or a directory.
2. 实现思路:我们可以重写一个类(CMyFileDialog)来继承QFileDialog,在调用时,利用QTreeView和QListView的组合使用来达到最终可同事选择目录和文件的目的,具体代码如下:
3. 具体代码
#这是CMyFileDialog.h #ifndef CMYFILEDIALOG_H #define CMYFILEDIALOG_H #include <QFileDialog> #include <QWidget> #include <QFileDialog> #include <QListView> #include <QTreeView> #include <QDialogButtonBox> class CMyFileDialog : public QFileDialog { Q_OBJECT public: explicit CMyFileDialog(QWidget *parent = nullptr); public slots: void slot_myAccetp(); signals: }; #endif // CMYFILEDIALOG_H
#这是CMyFileDialog.cpp #include "MyFileDialog.h" CMyFileDialog::CMyFileDialog(QWidget *parent) : QFileDialog(parent) { } void CMyFileDialog::slot_myAccetp() { QDialog::accept(); }
#调用MyDiaog的类 #include "widget.h" #include "ui_widget.h" #include <QDebug> #include "MyFileDialog.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } void Widget::on_pushButton_clicked() { CMyFileDialog *dialog =new CMyFileDialog(this); dialog->setOption(QFileDialog::DontUseNativeDialog,true); //支持多选 QListView *listView = dialog->findChild<QListView*>("listView"); if (listView) listView->setSelectionMode(QAbstractItemView::ExtendedSelection); QTreeView *treeView = dialog->findChild<QTreeView*>(); if (treeView) treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); QDialogButtonBox *button = dialog->findChild<QDialogButtonBox *>("buttonBox"); disconnect(button,SIGNAL(accepted()),dialog,SLOT(accept()));//使链接失效 connect(button,SIGNAL(accepted()),dialog,SLOT(slot_myAccetp()));//改成自己的槽 if(dialog->exec()==QDialog::Accepted) { qDebug()<<dialog->selectedFiles(); } }
4. 实现效果
我是在一个按钮的点击效果中调用的CMyFileDialog,选中目录或文件,打印路径。
点击按钮:
选择一个文件夹,点击右下角Open:
打印:
选择一个文件,点击Open:
打印:
参考:
QT QFileDialog允许选择同时选择多个文件和多个文件夹,也可以只选一个文件或一个文件夹 - 开发者知识库