qt拖拽事件重写

#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
上一篇:Python使用PaddleSpeech实现语音识别(ASR)、语音合成(TTS)


下一篇:【自动化】在WPF应用程序中使用MVVM框架实现Modbus协议通信