I've created a GraphicsItem
in a new class and have sent it to the GraphicsView
in another file. I've set the flag ItemIsMovable
as true and I am able to move the item.
How can I know where the user has moved it to? And, how can I then set the position manually?
[Essentially I have an item if the user moves it close enough to the right location I want to automatically move it to the right location]
In order to take the mouse's events I've used these functions:
void Detector::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Pressed = true;
update();
QGraphicsItem::mousePressEvent(event);
}
void Detector::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Pressed = false;
Moving = false;
update();
QGraphicsItem::mouseReleaseEvent(event);
}
void Detector::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Moving = true;
update();
QGraphicsItem::mouseMoveEvent(event);
}
My current thinking is to use the paint algorithm too, and create an if statement similar to the one shown below for Pressed (which changes the colour of the item when pressed).
void Detector::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QBrush darkBrown(QColor(83,71,65));
QBrush clickedBrown(QColor(122,83,66));
//fillBrush.setColor(darkBrown);
QPolygon DetectorPolygon;
DetectorPolygon << QPoint(0,0);
DetectorPolygon << QPoint(15,10);
DetectorPolygon << QPoint(50,10);
DetectorPolygon << QPoint(50,20);
DetectorPolygon << QPoint(15,20);
DetectorPolygon << QPoint(0,30);
QPen borderPen;
borderPen.setWidth(2);
borderPen.setColor(QColor(152,133,117));
painter->translate(780,425);
if (Pressed==true)
{
painter->setBrush(clickedBrown);
}
else
{
painter->setBrush(darkBrown);
}
if (Moving==true)
{
}
else
{
}
painter->setPen(borderPen);
painter->drawPolygon(DetectorPolygon);
}
Essentially: how do you get the coordinates of a QGraphicsItem
and how do you change them?
You can always call QPointF pos() const;
to get coordianates of item and void setPos(const QPointF &pos);
to change them. But it should be clear if you will just check documentation.