#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
void dragEnterEvent(QDragEnterEvent *);
void dropEvent(QDropEvent *);
private:
bool readFile(const QString &filename);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QDragEnterEvent>
#include <QMimeData>
#include <QUrl>
#include <QList>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//禁止textEdit拖放
ui->textEdit->setAcceptDrops(false);
this->setAcceptDrops(true);
}
Widget::~Widget()
{
delete ui;
}
void Widget::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat("text/uri-list"))
{
event->acceptProposedAction();
}
}
void Widget::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls(); //get File name
if(urls.empty())
return;
QString fileName = urls.first().toLocalFile();
readFile(fileName);
}
bool Widget::readFile(const QString &filename)
{
QFile file(filename) ;
if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
{
QMessageBox::warning(this,tr("Text Editor"),tr("Cant read file %1:%\n%2").arg(file.fileName()).arg(file.errorString()));
return false;
}
QTextStream in(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);//设置鼠标等待
ui->textEdit->setPlainText(in.readAll());
QApplication::restoreOverrideCursor();
}