(转载)http://www.cppblog.com/biao/archive/2011/10/23/158940.html
拖拽前:@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
#include "Widget.h"
#include "ui_Widget.h"
#include
#include
#include
#include
#include
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
dee->acceptProposedAction();
return true;
} else if (event->type() == QEvent::Drop) {
// [[3]]: 当放操作发生后, 取得拖放的数据
QDropEvent *de = dynamic_cast
QList
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);
}