增加拖放文件功能

This commit is contained in:
一二三 2023-06-20 22:27:42 +08:00
parent eb351c0fa1
commit c45f1852c6
2 changed files with 31 additions and 0 deletions

View File

@ -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<QUrl> urlList = mimeData->urls();
if (urlList.length() == 1)
{
QString fileName = urlList.first().toLocalFile();
if (!fileName.isEmpty())
{
loadTextFile(fileName);
}
}
}
}

View File

@ -5,6 +5,8 @@
#include <QThread>
#include <QMainWindow>
#include <QTableWidget>
#include <QDragEnterEvent>
#include <QMimeData>
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();