自定義QLineEdit支援檔案拖拽顯示檔案路徑
阿新 • • 發佈:2021-01-19
#pragma once #include <QtWidgets/Qwidget> #include <QLineEdit> #include <QDropEvent> #include <QMimeData> #include <QDragEnterEvent> class CustomLineEdit : public QLineEdit { Q_OBJECT public: CustomLineEdit(QWidget *parent = nullptr); ~CustomLineEdit(); protected: ///< 拖動檔案到視窗 觸發 void dragEnterEvent(QDragEnterEvent *event); ///< 拖動檔案到視窗移動檔案 觸發 void dragMoveEvent(QDragMoveEvent *event); ///< 拖動檔案到視窗釋放檔案觸發 void dropEvent(QDropEvent *event); };
#include "CustomLineEdit.h" CustomLineEdit::CustomLineEdit(QWidget *parent) : QLineEdit(parent) { setAcceptDrops(true); } CustomLineEdit::~CustomLineEdit() { } void CustomLineEdit::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasUrls()) event->acceptProposedAction(); //事件資料中存在路徑,方向事件 else event->ignore(); } void CustomLineEdit::dragMoveEvent(QDragMoveEvent *event) { } void CustomLineEdit::dropEvent(QDropEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasUrls()) { QList<QUrl> urls = mimeData->urls(); QString fileName = urls.at(0).toLocalFile(); setText(fileName); event->accept(); } else { event->ignore(); } }
執行結果: