拖拽前:@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
![Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅](http://img0.ph.126.net/EyrrndRYlwQO6GNoXsysqA==/6597694289262013455.png)
![Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅](http://img2.ph.126.net/z6PF7KJKMAKjMve_zEdwbw==/6598195666564064552.png)
![Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅](http://img1.ph.126.net/TW0P6Get7hJ710Pkgzs90g==/6597987858866635150.png)
![Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅](http://img1.ph.126.net/rqZ_YvmJnpWDLHJNNU2jhQ==/6597739369238748502.png)
![Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅](http://img1.ph.126.net/EdOX5tptIWHoeW5dGlFEVw==/6597776752634097193.png)
#include "Widget.h"
#include "ui_Widget.h"
#include <QUrl>
#include <QList>
#include <QtGui/QPixmap>
#include <QtGui/QDragEnterEvent>
#include <QtGui/QDropEvent>
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
ui->setupUi(this);
ui->label->installEventFilter(this);
ui->label->setAcceptDrops(true); // [[1]]: 使label可接受拖放操作
}
Widget::~Widget() {
delete ui;
}
bool Widget::eventFilter(QObject *watched, QEvent *event) {
if (watched == ui->label) {
if (event->type() == QEvent::DragEnter) {
// [[2]]: 当拖放时鼠标进入label时, label接受拖放的动作
QDragEnterEvent *dee = dynamic_cast<QDragEnterEvent *>(event);
dee->acceptProposedAction();
return true;
} else if (event->type() == QEvent::Drop) {
// [[3]]: 当放操作发生后, 取得拖放的数据
QDropEvent *de = dynamic_cast<QDropEvent *>(event);
QList<QUrl> urls = de->mimeData()->urls();
if (urls.isEmpty()) { return true; }
QString path = urls.first().toLocalFile();
// [[4]]: 在label上显示拖放的图片
QImage image(path); // QImage对I/O优化过, QPixmap对显示优化
if (!image.isNull()) {
image = image.scaled(ui->label->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
ui->label->setPixmap(QPixmap::fromImage(image));
}
return true;
}
}
return QWidget::eventFilter(watched, event);
}
转载:http://blog.csdn.net/hufeng825/article/details/5766703