简述
Qt使用QFileDialog类可以实现文件选择对话框,多文件选择对话框,以及文件夹选择对话框,就是没有多文件夹选择对话框,做的并不是很完美无法直接调用win下的原生对话框,下面将介绍一下Qt实现多选文件夹对话框的两种方式。
目录
- 使用QTreeView和QListView实现
- 调用MFC程序实现
方法一
使用以下代码可实现弹出文件夹多选对话框,但是此文件夹对话框有很多问题
- 界面样式很丑!
- 在某一台win电脑使用的时候会导致对话框打开后卡死,暂不清楚问题所在!
const QStringList fileDialog::openDirListDialog()
{
QFileDialog dialog(0, QObject::tr("Please select folder"), "./");
dialog.setWindowFlags(Qt::WindowStaysOnTopHint);
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
dialog.setFileMode(QFileDialog::DirectoryOnly);
QListView *listView = dialog.findChild<QListView*>();
QTreeView *treeView = dialog.findChild<QTreeView*>();
if (listView && treeView) {
listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
if(dialog.exec()) {
return dialog.selectedFiles();
}
}
return QStringList();
}
以下对话框样式为上述代码所调用!
方法二
1.在MFC下其实实现多选文件夹对话框并不难,使用如下代码在mfc下可直接调用。
#include "stdafx.h"
std::vector<CString> Get_path_dlg(HWND hwndOwner)
{
std::vector<CString> ans;
CWnd * pWnd = hwndOwner != NULL ? CWnd::FromHandle(hwndOwner) : NULL;
CFolderPickerDialog dlg(NULL, OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_ENABLESIZING, pWnd);
if (dlg.DoModal() == IDOK) {
POSITION pos = dlg.GetStartPosition();
while (pos) {
ans.push_back(dlg.GetNextPathName(pos));
}
}
return ans;
}
2.这里为了方便用Qt调用,这里吧mfc程序做成了socket客户端,Qt程序为服务端,进行发消息调用函数后返回路径写给服务端,以下为mfc代码和Qt调用方式。
①gitee地址
https://gitee.com/xiaoxin5210/DirListDialog
此地址包含mfc代码以及一个已编译出的.exe程序可通过Qt直接调用。
②使用Qt调用exe来打开对话框
//初始化服务端
void fileDialog::initServer()
{
QProcess* process = new QProcess(this);
process->start("taskkill -f -im *.exe"); //此exe名需自行修改,启动前先清空此程序
process->waitForFinished();
//QTcpServer* server;头文件包含
server = new QTcpServer(this);
server->listen(QHostAddress::Any, 11020);
connect(server, SIGNAL(newConnection()), this ,SLOT(onNewConnect()));
QProcess* p = new QProcess();
p->start("./CloudTransferTools", QStringList() << "123");
}
void fileDialog::onNewConnect()
{
qDebug() << "与对话框程序连接成功";
isConnect = true;
//QTcpSocket* socket;头文件包含
socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(onRead()));
}
//调用函数
void fileDialog::openDirListDialog()
{
if (!isConnect) { //这边是我的一个自行判断如果连接上此bool为true,如果连接不上发出去另作处理
emit signalSendDirPathList(QStringList(), isConnect);
return;
}
//如果连接上发送1,可自行编译mfc代码修改数据
socket->write("1");
}
//接收返回的路径
void fileDialog::onRead()
{
qint64 buf = socket->bytesAvailable();
QStringList dirPathList = QString::fromLocal8Bit(socket->read(buf)).split('|');
if (dirPathList.last() == "") {
dirPathList.removeLast();
}
emit signalSendDirPathList(dirPathList, isConnect);
}
以下图片为上述MFC程序打开的对话框!
结尾
以上为Qt调用多选文件夹对话框的两种方式,尝试过重写QFileDialong,看源码,始终在qt里面无法调用原生对话框,表示遗憾,以上代码拓展性较高自行修改。
新手上路,有不足或者有错误的地方还需大佬指教。
感谢阅读。