由于Qt程序中,拖拽功能被经常使用,网上很多例子都是直接对该类的两个虚函数进行重写:
protected:
virtual void dragEnterEvent(QDragEnterEvent *event) override;
virtual void dropEvent(QDropEvent *event) override;
但是,每个控件都对其这样书写使得代码简洁性降低,而且由于是重写,不得不在头文件中暴露上述两个虚函数。
所以,我一直在构思着,能不能写一个类,通过事件过滤器的方式,来简化代码呢?
答案是可以的。
话不多说,直接上代码:
dragdrophelper.h:
#ifndef DRAGDROPHELPER_H
#define DRAGDROPHELPER_H
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif
class DragDropHelper : public QObject
{
Q_OBJECT
public:
enum AllowedType { None = 0, File = 1, Directory = 2, All = File | Directory };
Q_DECLARE_FLAGS(AllowedTypes, AllowedType)
explicit DragDropHelper(QWidget *beneficiary, AllowedTypes types = File