【发布时间】:2016-04-21 08:36:23
【问题描述】:
我正在使用
void QGraphicsItem::installSceneEventFilter(QGraphicsItem * filterItem);
在 QgraphicsItem 上设置事件过滤器(请参阅itemChanged() in QGraphicsItem for a many different items)
现在,对于其中一些项目,我想限制移动,即更改项目的 x 和 y 位置,以便将用户限制在对象移动的某个区域。
我首先尝试修改事件:
(static cast <QGraphicsSceneMouseEvent*>(event))->setPos(QPoint(150, watched->y()));
整个处理程序是:
bool generic_graphic_item::sceneEventFilter(QGraphicsItem* watched, QEvent* event)
{
if(event->type() == QEvent::QEvent::GraphicsSceneMouseMove)
{
(static_cast<QGraphicsSceneMouseEvent*>(event))->setPos(QPointF(150, watched->y()));
//emit my_item_changed(watched); // signal that the item was moved
emit(item_pos_changed(watched, watched->x(), watched->y()));
}
return false; // pass the event to the original target item
}
但它没有工作。我也不确定隐藏在 QEvent::GraphicsSceneMouseEvent 后面的特定事件类。
然后我尝试在事件处理程序中调用watched->setX() 和watched->setY(),但这不是很受欢迎...我可以理解...
是否可以在场景事件处理程序中限制移动?
我已经读到QGraphicsItem::itemChange() 可以用来做到这一点,但后来我又回到了“itemChanged() in QGraphicsItem for a many different items”中描述的问题,即我怎样才能在不对每个项目进行子类化的情况下拥有许多项目的共同点。 .
非常感谢,
【问题讨论】:
-
感谢 Merlin069 抽出时间来回答。如果我按照你的建议使用 QEvent::GraphicsSceneMove,我什至没有得到带有新位置的信号 item_pos_changed。我的代码适用于此,即发出 item_pos_changed 信号。但我不知道如何将事件更改为我想要的鼠标位置,在上面的示例中,仅允许沿 x=150 的水平线移动
标签: c++ qt qgraphicsitem