PDA

View Full Version : Dragging a rectangle across a QGraphicsView



blooglet
14th November 2010, 11:15
I have a rectangle that I want to drag across a graphics view.


#ifndef BLOCK_H
#define BLOCK_H

#include <QGraphicsRectItem>

class Block : public QGraphicsRectItem
{
public:
Block(int x, int y);

// GUI events
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
};

#endif // BLOCK_H





#include <QPen>
#include <QLineF>
#include <QBrush>
#include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsSceneEvent>
#include <iostream>
#include "block.h"

Block::Block(int x, int y) {
this->setRect(x, y, 10, 10);
this->setBrush(QBrush(QColor(0, 0, 0)));
this->setPen(QPen(QColor(0, 0, 0)));
}

void Block::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
// Is move above threshold?
if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance())
return;

// Update x and y
this->setPos(event->scenePos().x(), event->scenePos().y());
}


Edit: I already figured out that I should be using scene coordinates, but when I initiate a drag the selected element doesn't stick to the top left of my mouse pointer as shown here:
http://www.screentoaster.com/watch/stUE5QREZKRFtXSVpYXllYX1BR/dragndrop

How can I fix this?

MarekR22
15th November 2010, 19:08
Make it more simple, check enum QGraphicsItem::ItemIsMovable (http://doc.trolltech.com/4.7/qgraphicsitem.html#GraphicsItemFlag-enum).

blooglet
16th November 2010, 10:19
D'oh... of course. Thanks!