I have a rectangle that I want to drag across a graphics view.
#ifndef BLOCK_H
#define BLOCK_H
#include <QGraphicsRectItem>
{
public:
Block(int x, int y);
// GUI events
};
#endif // BLOCK_H
#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
To copy to clipboard, switch view to plain text mode
#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);
}
// 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());
}
#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());
}
To copy to clipboard, switch view to plain text mode
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/s...X1BR/dragndrop
How can I fix this?
Bookmarks