QGraphicsItem中的itemChanged()用于许多不同的项目

时间:2013-11-08 13:47:06

标签: c++ qt qgraphicsitem

我的应用程序包含QGraphisScene中的许多不同项目。 这些项目将是矩形,椭圆,像素图或任何继承自QGraphicsItem的内容。 用户可以移动这些项目。 (每个QGraphicsItem::ItemIsMovable标志都已设置)。

应用程序需要获取事件(回调,信号或其他)以获得新职位。

如何一次性为所有这些可能的项目重载itemChanged()方法?我想避免继承子类化我的每个可能的项目(即为QGraphicsEllipseItem做一个派生类,为QGraphicsPixmapItem做另一个,为以后的任何项做一个子类......)?

我希望能够告诉:每次QGraphicsItem(或从中派生的任何内容)发生变化时,请调用我的函数:

 my_item_changed(QGraphicItem* the_change_item,...).

然后能够添加不同的项目类型,而不必再担心...

任何提示?

1 个答案:

答案 0 :(得分:1)

您可以在QGraphicsItems上安装事件过滤器。特别是,您将要使用此功能: -

void QGraphicsItem::installSceneEventFilter(QGraphicsItem * filterItem);

正如Qt文档所述,这是一个使用它的例子: -

QGraphicsScene scene;
QGraphicsEllipseItem *ellipse = scene.addEllipse(QRectF(-10, -10, 20, 20));
QGraphicsLineItem *line = scene.addLine(QLineF(-10, -10, 20, 20));

line->installSceneEventFilter(ellipse);
// line's events are filtered by ellipse's sceneEventFilter() function.

ellipse->installSceneEventFilter(line);
// ellipse's events are filtered by line's sceneEventFilter() function.

基于此,创建一个派生自QGraphicsItem的类,它可以先接收事件。对于添加到场景中的每个项目,请调用installSceneEventFilter: -

mySceneEventItem.installSceneEventFilter(pGraphicsItem);

接下来,您的eventFilter对象将覆盖该函数: -

bool QGraphicsItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event)
{
    if(event->type() == QEvent::GraphicsSceneMove)
    {
        emit my_item_changed(watched); // signal that the item was moved
    }

    return false; // pass the event to the original target item
}

这允许您检查事件并处理您感兴趣的事件。如果您从sceneEventFilter返回false,则事件将在您处理之后传递给原始对象; return true将阻止事件被传递。