我正在尝试适本地限制 QGraphicsItem
(特别是 QGraphicsRectItem
)的移动,而不更改 native 行为以用作 X 轴上的滚动条。
我尝试覆盖 mouseMoveEvent
函数,但随后我需要重写矩形在 X 和 Y 方向上的行为。充其量,我可以使用鼠标将矩形捕捉到一个位置。 (此处矩形将捕捉,因此鼠标将其保持在中点):
void SegmentItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
setY(0);
setX(event->scenePos().x() - boundingRect().width()/2);
}
我正在查看 itemChange
,如 here 所述,但它看起来有点笨重而且不够优雅。
编辑:这应该可以工作,但我目前无法强制它工作。
有没有办法只限制 y 轴的移动? (我还需要为滚动条创建止点,但稍后。)
最佳答案
我修改了 itemChange
类引用页面中的代码,并对其进行了增强,使我的 QGraphicsRectItem
的所有四个角都位于 QGraphicsScene
:
QVariant SegmentItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
rect.setWidth(rect.width() - boundingRect().width());
rect.setHeight(0);
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(2);
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
关于c++ - 使用 mouseMoveEvent 限制 QGraphicsItem 的移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221482/