仅通过X轴移动对象

仅通过X轴移动对象

我仅通过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的文档。它说:



而且在我们的代码中,我看不到您已经设置了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/

10-09 13:27