Qt Drop event not firing

人走茶凉 提交于 2019-12-11 07:55:34

问题


Drop event will not happen, although `setAcceptDrops' has been called. The following code is based on a widget project created with Qt 5.12.0. After adding in dropEvent() function the cpp file becomes

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug> // added

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAcceptDrops(true); // added
}

MainWindow::~MainWindow()
{
    delete ui;
}

// added; in .h it is in `protected:' section
void MainWindow::dropEvent(QDropEvent *event)
{
    qDebug() << "dropEvent";
}

What am I missing? I have been struggling for a few days... Thanks in advance.


回答1:


You have to overwrite the dragEnterEvent method that allow you to filter by the data type, by the source, by the type of action. In the following example, everything is accepted:

*.h

// ...
protected:
    void dropEvent(QDropEvent *event) override;
    void dragEnterEvent(QDragEnterEvent *event) override;
// ...

*.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAcceptDrops(true); // added
}

// ...
void MainWindow::dropEvent(QDropEvent *event)
{
    qDebug() << "dropEvent" << event;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

For more detail I recommend you read Drag and Drop.



来源:https://stackoverflow.com/questions/53870847/qt-drop-event-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!