gpt4 book ai didi

c++ - QGraphicsItem 仅通过 X 轴移动对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:31 27 4
gpt4 key购买 nike

我在仅通过 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 );
}

但它不起作用。我是 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 );
}

感谢您的回答。

最佳答案

阅读 QGraphicsItem::ItemPositionChange 的文档.它说:

The item's position changes. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's local position changes, relative to its parent (i.e., as a result of calling setPos() or moveBy()). The value argument is the new position (i.e., a QPointF). You can call pos() to get the original position. Do not call setPos() or moveBy() in itemChange() as this notification is delivered; instead, you can return the new, adjusted position from itemChange(). After this notification, QGraphicsItem immediately sends the ItemPositionHasChanged notification if the position changed.

在我们的代码中我没有看到你设置了这个 ItemSendsGeometryChanges 标志,所以正确的构造函数是这样的:

CircleItem::CircleItem() // where is parent parameter?
{
RectItem = new RoundRectItem();
MousePressed = false;
setFlag(ItemIsMovable | ItemSendsGeometryChanges);
}

关于c++ - QGraphicsItem 仅通过 X 轴移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com