Q 项目仅通过 X 轴移动对象
QGraphicsItem move object only through X axis
我只通过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);
}
相关文章:
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 如果这不是类的"复制构造函数",是否可以移动对象?
- 我可以从向量的开头移动对象吗?为什么不呢
- 为什么可以使用已删除的移动构造函数和赋值运算符移动对象?
- 使用参数将仅可移动对象捕获到 lambda
- 初始化不可移动对象数组:为什么这样的代码无法在 GCC 上编译?
- c++ 从成员函数创建新线程并移动对象和整个对象
- 返回unique_ptr或只是移动对象
- 将 OpenGL 实例化图形与移动对象一起使用
- 如何在给定两个点的线上移动对象?
- 使用文件描述符移动对象
- 为什么移动对象不会使其为空?
- 被引用的移动对象
- Maya c++ API,移动对象?
- 为什么传递std ::移动(对象)和此对象的成员函数会导致sigsegv
- 命令模式:如何进行连续操作?(例如,移动对象)
- 返回具有显式构造函数的不可复制的不可移动对象
- 如何在 C++ 中的特定边界内移动对象
- 在阵列中向上移动对象
- DirectX 11 基于旋转移动对象