Function
Drag and drop multiple files into the interface to display the path of the files.
accomplish
1. Enable form drop operation
this->setAcceptDrops(true);//启用放下操作
2. Rewrite the dragEnterEvent() function to filter drag events
void dragEnterEvent(QDragEnterEvent *e);
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
//对拖放事件进行筛选
if (true)
{
e->acceptProposedAction(); //放行,否则不会执行dropEvent()函数
}
}
3. Rewrite the dropEvent() function to handle drag events
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. Remove duplicate files
QList stores the file path. Since Qset has no duplicates, it can be converted to set first, and then converted back to list.
pathlist = pathlist.toSet().toList();
Effect
UI layout
final effect
source code
head File
#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
Source File
#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;
}
The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓