c++ - 更改场景事件处理程序中的 QGraphicsItem 位置?

标签 c++ qt qgraphicsitem

我正在使用

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”中描述的问题。 ',即我如何在不对每个项目进行子类化的情况下对许多项目拥有这个共同点......

非常感谢,

最佳答案

您在此问题中发布的代码是对鼠标移动事件的响应。对于您描述的您想做的事情,我建议您检查使用 QEvent::GraphicsSceneMove 移动小部件的事件:-

if(event->type() == QEvent::GraphicsSceneMove)
{
    // set the position of the item.
}

关于c++ - 更改场景事件处理程序中的 QGraphicsItem 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180302/

相关文章:

c++ - 已分配但未初始化

c++ - 也许 monad : how to avoid storing T-typed value in Maybe<T> instance?

c++ - 在其他窗口中使用 QApplication::activeWindow->winId() 时,QT 5.5 程序崩溃

c++ - QtQuick ChartView QML 对象段错误在加载期间导致 QML 引擎段错误

c++ - 用嵌入式私有(private)类覆盖 Qt 类

c++ - 如何设置 QGraphicsItemGroup 的显示范围?

c++ - 查找 QGraphicsItem 的屏幕位置

c++ - g++ 同时链接静态库和非静态库

c++ - Visual Studio 2017 警告说异常被基类捕获,但事实并非如此

c++ - 通过 QGraphicsItem 剪辑 QPainterPath