#include "mainwindow.h"
#include <QLabel>
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include <QDrag>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QPainter>
#include <QMimeData>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAcceptDrops(true); //设置窗口部件可以接收拖入
QLabel * label = new QLabel(this);
QPixmap pix("..//imagedragdrop/logo.png");
label->setPixmap(pix);
label->resize(pix.size());
label->move(100,100);
label->setAttribute(Qt::WA_DeleteOnClose); //当窗口关闭时销毁图片
}
MainWindow::~MainWindow()
{
delete ui;
}
//鼠标按下事件
void MainWindow::mousePressEvent(QMouseEvent *event)
{
//第1步:获取图片
//将鼠标指针所在位置的部件强制转换为Label类型
QLabel * child = static_cast<QLabel *>(childAt(event->pos()));
if(!child->inherits("QLabel"))
return;
QPixmap pixmap = *child->pixmap();
//第2步:自定义MIME类型
QByteArray itemData;
QDataStream dataStream(&itemData,QIODevice::WriteOnly);
//将图片信息,位置信息输入到自己数组中
dataStream<<pixmap<<QPoint(event->pos()-child->pos());
//第3步:将数据放入QMimeData中
QMimeData *mimeData = new QMimeData;
//将字节数组放入QMimeData中,这里的MIME类型是我们自己定义的
mimeData->setData("myimage/png",itemData);
//第4步:将QMimeData数据放入QDrag中
QDrag *drag = new QDrag(this); //创建QDrag用来移动数据
drag->setMimeData(mimeData);
drag->setPixmap(pixmap); //在移动过程中显示图片,若不设置则默认显示一个小矩形
drag->setHotSpot(event->pos()-child->pos()); //拖动时鼠标指针的位置不变
//第5步:给原图添加阴影
QPixmap tempPixmap = pixmap;
QPainter painter;
painter.begin(&tempPixmap);
//在图片的外接矩形中添加一层透明的淡黑色形成阴影效果
painter.fillRect(pixmap.rect(),QColor(127,127,127,127));
painter.end();
child->setPixmap(tempPixmap); //在移动图片过程中,让原图片有一层黑色阴影
//第6步:执行拖放操作
if(drag->exec(Qt::CopyAction|Qt::MoveAction,Qt::CopyAction)==Qt::MoveAction)
{
child->close(); //如果是移动操作,那么拖放完成后关闭原标签
}
else
{
child->show(); //如果是复制操作,那么拖放完成后显示标签
child->setPixmap(pixmap); //显示原图片,不再使用阴影
}
}
//拖入事件
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat("myimage/png"))
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
event->ignore();
}
}
//拖动事件
void MainWindow::dragMoveEvent(QDragMoveEvent *event)
{
if(event->mimeData()->hasFormat("myimage/png"))
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
event->ignore();
}
}
//放下事件
void MainWindow::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasFormat("myimage/png"))
{
QByteArray itemData = event->mimeData()->data("myimage/png");
QDataStream dataStream(&itemData,QIODevice::ReadOnly);
QPixmap pixmap;
QPoint offset;
dataStream>>pixmap>>offset;
QLabel * newLabel = new QLabel(this);
newLabel->setPixmap(pixmap);
newLabel->resize(pixmap.size());
newLabel->move(event->pos()-offset);
newLabel->show();
newLabel->setAttribute(Qt::WA_DeleteOnClose); //当窗口关闭时销毁图片
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
event->ignore();
}
}
MechMaster
- 粉丝: 3w+
- 资源: 58
评论0