Q 项目仅通过 X 轴移动对象

QGraphicsItem move object only through X axis

本文关键字:移动 对象 项目      更新时间:2023-10-16

我只通过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的新手,所以我不知道如何改变这件事。这是我的图形项的代码:

#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 的文档。它说:

项目的位置将更改。如果 启用"项目发送几何更改"标志,以及当项目的本地 相对于其父级的位置变化(即,由于调用 setPos() 或 moveBy())。值参数是新位置(即 QPointF)。你可以调用 pos() 来获取原始位置。不要打电话 setPos() 或 moveBy() 在 itemChange() 中,因为此通知是 交付;相反,您可以从以下位置返回新的调整位置 itemChange()。此通知后,QGraphicsItem 立即发送 如果位置更改,则"项目位置已更改"通知。

在我们的代码中,我没有看到您设置了此ItemSendsGeometryChanges标志,因此请像这样更正构造函数:

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