c++ - 将 QGraphicsItems 附加到 QGraphicsItemGroup 会导致崩溃

标签 c++ qt

这是我的第一篇文章。我最近开始将 QT 与 C++ 结合使用。印象深刻。我有一个似乎无法解决的问题。基本上,我试图将许多 QGraphicsItems 组织成两个 QGraphicsItemGroups。使用 QGraphicsView 上的 QGraphicsScene 显示项目。创建项目和显示项目就像一个魅力。但是,当我添加分组时,程序每次都会在命令上崩溃。添加分组的原因是稍后能够选择要在 paintevent 中呈现的项目。相关代码如下。

QGraphicsScene * scene;
scene = new QGraphicsScene(this);
ui.graphicsView->setScene(scene);

QBrush whiteBrush;
QBrush imageBrush;
QPen blackPen;
whiteBrush = QBrush(Qt::white);
imageBrush = QBrush(Qt::lightGray);
blackPen = QPen(Qt::black);
blackPen.setWidth(1);

QGraphicsItemGroup * cliGroup;
QGraphicsItemGroup * alfGroup;
cliGroup = new QGraphicsItemGroup;
alfGroup = new QGraphicsItemGroup;
scene->addItem(cliGroup);
scene->addItem(alfGroup);

QGraphicsPolygonItem *poly;
poly =  scene->addPolygon(polyF, blackPen, imageBrush);
cliGroup->addToGroup(poly);        //line it crashes on

我怀疑它与在场景中创建多边形然后将它们添加到 QGraphicsItemGroup 有关,尽管我不知道如何改变它以使其工作。从那以后,我采用了一种不太优雅的解决方案,该解决方案基于根据类型过滤场景中的项目,但这是短期且困惑的。有什么建议吗?

最佳答案

来自QGraphicsItemGroup文档:

There are two ways to construct an item group. The easiest and most common approach is to pass a list of items (e.g., all selected items) to QGraphicsScene::createItemGroup(), which returns a new QGraphicsItemGroup item. The other approach is to manually construct a QGraphicsItemGroup item, add it to the scene calling QGraphicsScene::addItem(), and then add items to the group manually, one at a time by calling addToGroup().

因此,正如皮特建议的那样,我会尝试以下方法:

QList<QGraphicsItem*> groupItems;
groupItems.append(poly); // add more items if you want
// Finally  construct the group
QGraphicsItemGroup * cliGroup = scene->createItemGroup(groupItems); 

关于c++ - 将 QGraphicsItems 附加到 QGraphicsItemGroup 会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8225800/

相关文章:

c++ - 当期望 T 作为模板化参数时,make_tuple 将类型 T 作为 T&& 传递

c++ - 嵌入式 Lua - 超时流氓脚本(例如无限循环) - 一个例子吗?

c++ - 复合类 C++ 中的冗余代码

c++ - cdb.exe 位于 Visual Studio 2013 中的什么位置?

c++ - QApplication::mouseButtons 的线程安全性和延迟安全性如何?

c++ - Qt - 没有匹配函数来调用 ‘QVariant::QVariant(MyClass&)’

Visual Studio 11 中的 c++11 thread_local 关键字支持

c++ - 基于 pthread 的多功能多线程实用程序库

qt - 当 QGraphicsScene::addPixmap 只接受 const QPixmap 时如何使用它?

c++ - 使用 QLineEdit 获取密码