zoukankan      html  css  js  c++  java
  • Qt:拖拽图片到QLabel上并显示(转)

    拖拽前:@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

    Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅 
     
    拖拽图片到窗口的label里,显示效果如下:
    Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅
     
     
    Qt已经提供了强大的拖拽功能,实现如上效果,只需要很简单的几步即可。
    1. 使用Qt Creator创建一个窗口,在里面放置一个QLabel,如下图:
     
    Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅
     
     
    ^_^,里面的QLabel与你的不一样?
    在此加个小知识点,给label加上style sheet,像CSS一样简单的就可以做出上图效果,按下图操作即可:
    Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅
     
    Qt:拖拽图片到QLabel上并显示 - 柳北风儿 - 柳北风儿~~~~~~~欲宇仙炅
     
     
    图上了这么多,实现代码如下,几步即可完成,是不是很简单?:
     

    #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); // QImageI/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

  • 相关阅读:
    38、面向对象设计模式之策略模式(Strategy)
    37、面向对象设计模式之代理模式(Proxy)
    36、面向对象设计模式之观察者模式(Observer)
    35、面向对象设计模式之抽象工厂(Abstract Factory)设计模式
    34、面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较
    Chisel插件
    Git 常用命令
    oh_my_zsh
    一般xcode报错
    sqlite3 语法
  • 原文地址:https://www.cnblogs.com/veins/p/3185389.html
Copyright © 2011-2022 走看看