我有一个问题只能通过x轴移动我的对象.我知道你需要有功能的东西QVariant itemChange ( GraphicsItemChange change, const QVariant & value ).我找到了这样的东西:
QVariant CircleItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange)
return QPointF(pos().x(), value.toPointF().y());
return QGraphicsItem::itemChange( change, value );
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我是Qt的新手,所以我不知道,如何改变这个东西.这是我的GraphicsItem的代码:
#include "circleitem.h"
CircleItem::CircleItem()
{
RectItem = new RoundRectItem();
MousePressed = false;
setFlag( ItemIsMovable );
}
void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
if( MousePressed )
{
painter->setBrush( QBrush( QColor( 0, 0, 255 ) ) );
painter->setPen( QPen( QColor( 0, 0, 255 ) ) );
}
else
{
painter->setBrush( QBrush( QColor( 255, 255, 255 ) ) );
painter->setPen( QPen( QColor( 255, 255, 255 ) ) );
}
painter->drawEllipse( boundingRect().center(), boundingRect().height() / 4 - 7, boundingRect().height() / 4 - 7 );
}
QRectF CircleItem::boundingRect() const
{
return RectItem->boundingRect();
}
void CircleItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
MousePressed = true;
update( QRectF().x(), boundingRect().y(), boundingRect().width(), boundingRect().height() );
QGraphicsItem::mousePressEvent( event );
}
void CircleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
MousePressed = false;
update( QRectF().x(), boundingRect().y(), boundingRect().width(), boundingRect().height() );
QGraphicsItem::mouseReleaseEvent( event );
}
QVariant CircleItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange)
return QPointF(pos().x(), value.toPointF().y());
return QGraphicsItem::itemChange( change, value );
}
Run Code Online (Sandbox Code Playgroud)
谢谢回答.
阅读QGraphicsItem :: ItemPositionChange的文档.它说:
项目的位置发生变化.如果启用了ItemSendsGeometryChanges标志,并且该项的本地位置相对于其父项发生更改(即,作为调用setPos()或moveBy()的结果),则会发送此通知.value参数是新位置(即QPointF).你可以调用pos()来获得原始位置.交付此通知时,请勿在itemChange()中调用setPos()或moveBy(); 相反,您可以从itemChange()返回新的,调整后的位置.在此通知之后,如果位置发生更改,QGraphicsItem会立即发送ItemPositionHasChanged通知.
在我们的代码中,我没有看到你设置了这个ItemSendsGeometryChanges标志,所以正确的构造函数如下:
CircleItem::CircleItem() // where is parent parameter?
{
RectItem = new RoundRectItem();
MousePressed = false;
setFlag(ItemIsMovable | ItemSendsGeometryChanges);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
870 次 |
| 最近记录: |