本篇内容主要讲解“QT如何实现多文件拖拽获取路径”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“QT如何实现多文件拖拽获取路径”吧!
将多个文件拖拽进界面中,显示文件的路径。
1、启用窗体放下操作
this->setAcceptDrops(true);//启用放下操作
2、重写dragEnterEvent()函数,用于筛选拖拽事件
void dragEnterEvent(QDragEnterEvent *e);
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
//对拖放事件进行筛选
if (true)
{
e->acceptProposedAction(); //放行,否则不会执行dropEvent()函数
}
}
3、重写dropEvent()函数,用于处理拖拽事件
void dropEvent(QDropEvent *e);
void MainWindow::dropEvent(QDropEvent *e)
{
QList<QUrl> urls = e->mimeData()->urls();
if(urls.isEmpty())
return ;
qDebug()<< urls.size();
foreach (QUrl u, urls)
{
QString filepath = u.toLocalFile();
pathlist.append(filepath);
}
}
4、重复文件去除
QList存储文件路径,由于Qset是没有重复项的,故可先转换为set,再转回为list即可。
pathlist = pathlist.toSet().toList();
UI布局
最后效果
头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextEdit>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void dragEnterEvent(QDragEnterEvent *e);
void dropEvent(QDropEvent *e);
private slots:
void on_pushButton_upload_clicked();
private:
Ui::MainWindow *ui;
QList<QString> pathlist;
};
#endif // MAINWINDOW_H
源文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDragEnterEvent>
#include <QFile>
#include <QDebug>
#include <QMimeData>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->textEdit->setAcceptDrops(false); //禁用控件的放下操作
this->setAcceptDrops(true);//启用放下操作
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
//对拖放事件进行筛选
if (true)
{
e->acceptProposedAction(); //放行,否则不会执行dropEvent()函数
}
}
void MainWindow::dropEvent(QDropEvent *e)
{
QList<QUrl> urls = e->mimeData()->urls();
if(urls.isEmpty())
return ;
qDebug()<< urls.size();
foreach (QUrl u, urls)
{
QString filepath = u.toLocalFile();
pathlist.append(filepath);
}
//去掉重复路径
pathlist = pathlist.toSet().toList();
ui->textEdit->clear();
for(int i=0;i<pathlist.size();++i)
{
QString path = pathlist.at(i);
ui->textEdit->append(path);
}
}
void MainWindow::on_pushButton_upload_clicked()
{
qDebug()<<pathlist;
}
到此,相信大家对“QT如何实现多文件拖拽获取路径”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。