我在一个新类中创建了一个GraphicsItem
,并将其发送到另一个文件中的GraphicsView
。我已经将标志ItemIsMovable
设置为true,并且我能够移动该项目。
我如何知道用户已将其移动到何处?然后,我如何手动设置位置?
[本质上,如果用户将项目移动到足够近的正确位置,我会自动将其移动到正确的位置,我就有一个项目]
为了获取鼠标的事件,我使用了以下功能:
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);
}
我目前的想法是也使用绘制算法,并创建一个类似于下面为Pressed显示的if语句(按下时会改变项目的颜色)。
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);
}
本质上:如何获得QGraphicsItem
的坐标,以及如何更改它们?
您可以始终调用QPointF pos() const;
来获取项的坐标,并调用void setPos(const QPointF &pos);
来更改它们。但是,如果您只查看文档,应该很清楚。