From c45f1852c6087e8ad21a5e51183bcc6fa31626ca Mon Sep 17 00:00:00 2001 From: Crimson Date: Tue, 20 Jun 2023 22:27:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=8B=96=E6=94=BE=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mainwindow.cpp | 27 +++++++++++++++++++++++++++ mainwindow.h | 4 ++++ 2 files changed, 31 insertions(+) diff --git a/mainwindow.cpp b/mainwindow.cpp index 7bf71e6..dd7073b 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -13,6 +13,8 @@ MainWindow::MainWindow(QWidget *parent) { ui->setupUi(this); + setAcceptDrops(true); // 允许窗口接受拖放事件 + connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::onOpenButtonClicked); connect(ui->actionSave, &QAction::triggered, this, &MainWindow::onSaveButtonClicked); } @@ -156,3 +158,28 @@ void MainWindow::onSaveButtonClicked() } } } + +void MainWindow::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->mimeData()->hasUrls()) + { + event->acceptProposedAction(); + } +} + +void MainWindow::dropEvent(QDropEvent *event) +{ + const QMimeData* mimeData = event->mimeData(); + if (mimeData->hasUrls()) + { + QList urlList = mimeData->urls(); + if (urlList.length() == 1) + { + QString fileName = urlList.first().toLocalFile(); + if (!fileName.isEmpty()) + { + loadTextFile(fileName); + } + } + } +} diff --git a/mainwindow.h b/mainwindow.h index 74878dc..e933317 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -5,6 +5,8 @@ #include #include #include +#include +#include QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } @@ -18,6 +20,8 @@ public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void loadTextFile(const QString& fileName); + void dragEnterEvent(QDragEnterEvent *event); + void dropEvent(QDropEvent *event); private slots: void onOpenButtonClicked();