环境:vs2019+qt5.14.2
坑哦。让我搞了好久。各种不执行,最后发现,不用vs调制,直接运行exe就能接收拖拽了。
记录一下,感觉是qt的bug。上代码。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextEdit>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
protected:
void dragEnterEvent(QDragEnterEvent* e) override;
void dragLeaveEvent(QDragLeaveEvent* e) override;
void dragMoveEvent(QDragMoveEvent* event) override;
void dropEvent(QDropEvent* e) override;
private:
bool readFile(const QString& fileName);
QTextEdit* textEdit;
};
#endif // MAINWINDOW_H
#include <QDragEnterEvent>
#include <QMimeData>
#include <QFile>
#include <QUrl>
#include <QDebug>
#include "QtWidgetsApplication5.h"
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)
{
//this->setMouseTracking(true); 不加也行
textEdit = new QTextEdit;
setCentralWidget(textEdit);
textEdit->setAcceptDrops(false);
setAcceptDrops(true);
setWindowTitle(tr("Text Editor"));
}
MainWindow::~MainWindow()
{
}
void MainWindow::dragEnterEvent(QDragEnterEvent* e)
{
qDebug() << "dragEnterEvent" << e->mimeData();
e->accept();
if (e->mimeData()->hasFormat("text/uri-list"))
e->acceptProposedAction();
}
void MainWindow::dragLeaveEvent(QDragLeaveEvent* e)
{
qDebug() << "dragLeaveEvent";
//e->accept(); 不加也行
}
void MainWindow::dragMoveEvent(QDragMoveEvent* event)
{
event->setDropAction(Qt::MoveAction);
//event->accept(); 不加也行
}
void MainWindow::dropEvent(QDropEvent* e) //释放对方时,执行的操作
{
//e->accept(); 不加也行
QList<QUrl> urls = e->mimeData()->urls();
if (urls.isEmpty())
return;
QString fileName = urls.first().toLocalFile();
foreach(QUrl u, urls) {
qDebug() << u.toString();
}
qDebug() << urls.size();
if (fileName.isEmpty())
return;
if (readFile(fileName))
setWindowTitle(tr("%1 - %2").arg(fileName).arg("Drag File"));
}
bool MainWindow::readFile(const QString& fileName) //读文件
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text))
return false;
QByteArray data;
data = file.readAll();
textEdit->setText(QString::fromLocal8Bit(data));
return true;
}
#include "QtWidgetsApplication5.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
运行结果: