1.qt中的拖拽事件步骤
1设置接受拖拽
2重写事件就可以了
3其他的控件如何要可以套模板
2.例子
#include <QGroupBox>
#include <QObject>
#include <QDragEnterEvent>
#include <QFileInfo>
#include <QMimeData>//重写,指出拖拽指定的文件进来,可以自己命名什么文件可以拖进来class DGroupBox : public QGroupBox
{Q_OBJECT
public:DGroupBox(){setAcceptDrops(true);}protected:void dragEnterEvent(QDragEnterEvent *event) override{QList<QUrl> urls = event->mimeData()->urls();bool acceptDrop = false;for (const QUrl &url : urls) {QString filePath = url.toLocalFile();//if (filePath.endsWith(".txt", Qt::CaseInsensitive))if(QFileInfo(filePath).fileName() == m_acceptFileName){acceptDrop = true;event->setDropAction(Qt::CopyAction);event->accept();break;}}if (!acceptDrop) {event->setDropAction(Qt::IgnoreAction);event->ignore();}}void dragMoveEvent(QDragMoveEvent *event) override{switch (event->dropAction()) {case Qt::CopyAction:event->accept();setCursor(Qt::CursorShape::DragCopyCursor);break;default:event->ignore();setCursor(Qt::ForbiddenCursor);break;}}void dropEvent(QDropEvent *event) override{QList<QUrl> urls = event->mimeData()->urls();if (!urls.isEmpty()) {for (const QUrl &url : urls) {QString filePath = url.toLocalFile();//if (filePath.endsWith(".txt", Qt::CaseInsensitive))if(QFileInfo(filePath).fileName() == m_acceptFileName){// 将文件路径设置为QLabel的文本emit accpetFile(filePath);}}}event->acceptProposedAction();}
signals:void accpetFile(QString filePath);public:void setAcceptFileName(QString name){m_acceptFileName = name;}
private:QString m_acceptFileName = "encrypted_data.dat";};#endif // DGROUPBOX_H