gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:05:22 25 4
gpt4 key购买 nike

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

应用程序需要获取事件(回调、信号或其他)才能获得新位置。

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

我想知道:每次 QGraphicsItem(或任何派生自它的东西)发生变化时,调用我的函数:

 my_item_changed(QGraphicItem* the_change_item,...).

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

有什么提示吗?

最佳答案

您可以在 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,事件将在您处理后传递给原始对象;返回 true 将阻止事件继续传递。

关于c++ - QGraphicsItem 中的 itemChanged() 用于许多不同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19860582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com