Qt:拖拽图片到QLabel上并显示

转载自:http://www.cppblog.com/biao/archive/2011/10/23/158940.html

仅供参考!

实现代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 
#include 
#include 
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->label->installEventFilter(this);
    ui->label->setAcceptDrops(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}


bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->label) {
            if (event->type() == QEvent::DragEnter) {
                // [[2]]: 当拖放时鼠标进入label时, label接受拖放的动作
                QDragEnterEvent *dee = dynamic_cast(event);
                dee->acceptProposedAction();
                return true;
            } else if (event->type() == QEvent::Drop) {
                // [[3]]: 当放操作发生后, 取得拖放的数据
                QDropEvent *de = dynamic_cast(event);
                QList 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 QMainWindow::eventFilter(watched, event);
}
运行效果:

Qt:拖拽图片到QLabel上并显示_第1张图片


你可能感兴趣的:(Qt,C++)