Qt5 拖拽
程序员文章站
2024-01-02 21:17:40
...
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextEdit>
#include <QUrl>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool ReadFile(QString strPath);
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
private:
Ui::MainWindow *ui;
QTextEdit *m_cTextEdit = NULL;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDragEnterEvent>
#include <QMimeData>
#include <QDebug>
#include <QList>
#include <QByteArray>
#include <QTextStream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_cTextEdit = new QTextEdit(this);
setCentralWidget(m_cTextEdit);
m_cTextEdit->setAcceptDrops(false);
this->setAcceptDrops(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat("text/uri-list"))
//拖拽时间已经接受了用户的拖拽动作
//if not the code,then dropEvent would not be called
event->acceptProposedAction();
}
void MainWindow::dropEvent(QDropEvent *event)
{
qDebug() << "dropEvent";
QList<QUrl> urls = event->mimeData()->urls();
if(urls.isEmpty())
return;
QString fileName = urls.first().toLocalFile();
if(fileName.isEmpty())
return;
qDebug() << tr("%1 -- %2").arg(fileName).arg(fileName);
if(ReadFile(fileName))
setWindowTitle(tr("%1 -- %2").arg(fileName).arg("Drag File"));
}
bool MainWindow::ReadFile(QString strPath)
{
if(strPath.isEmpty())
return false;
QFile file(strPath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
// QByteArray text = file.readAll();//这样使用会产生中文乱码,应该使用下面的方式
QTextStream in(&file);//想要读写文件不出现乱码尽量使用这种方式
m_cTextEdit->setText(in.readAll());
in.flush();
file.close();
return true;
}