QDrag 使用一例
??????? 在Qt中可以使用QDrag 来拖动操作Graphics各个元素,以此实现方便的拖动操作。
我们可以从QGraphicsItem 重载 mousePressEvent 来做开始拖动的操作,比如
void Item::mousePressEvent(QGraphicsSceneMouseEvent *event){ Qt::MouseButtons btn = event->buttons(); if(btn == Qt::LeftButton){ QDrag* drag = new QDrag(this->scene()); QMimeData* data = new QMimeData(); drag->setMimeData(data); QPixmap pixmap(":image.png"); QPainter painter(&pixmap); drag->setPixmap(pixmap); //这里设置拖拽时跟随鼠标的图片 drag->setHotSpot(QPoint(15,15)); //设置跟随图片的中心点 drag->exec(); //开始拖拽, 释放拖拽执行下面代码 #ifdef Q_WS_WIN //linux系统中你不能删除drag,删除会由系统自动执行(自己调试得知,可能不正确) delete drag;//注意 上面QMimeData* data这里也会一并删除 #endif? }}?这样当我们鼠标按下这个Item时候 拖动就可以开始了
我们有了可以拖的,还必须有去接收这个拖拽的东西,因为只有定义了允许放东西的地方。你才能把东西放里面
于是我们重载另一QGraphicsItem 的dropEvent函数
void DragReceiverItem::dropEvent(QGraphicsSceneDragDropEvent *event){ qDebug() << "drop event " ; qDebug() << "pos = " << event->pos(); qDebug() << "scene pos = " << event->scenePos(); qDebug() << "screen pos = " << event->screenPos(); qDebug() << "mime data = " << event->mimeData(); }?可以看到 mimeData也会随着QGraphicsSceneDragDropEvent传递过来,这样拖拽就可以传递一些我们自己的数据。
还有一点要注意,就是QGraphicsItem必须设置 accpetDrop 为true之后才能触发DropEvent等事件
然后我们还有很多地方可以定制,比如
void DragReceiverItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event){ qDebug() << "拖到 当前Item里面时";}void DragReceiverItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event){ qDebug() << "拖到当前item外面时";}void DragReceiverItem::dragMoveEvent(QGraphicsSceneDragDropEvent *event){ qDebug() << "拖到当前item里面的移动时";}?综上,我们拖拽操作的拖动方与接收方都定义好了,我们就可以方便的在Qt Graphics中使用拖拽操作了。