【问题标题】:QGraphicsScene - deleting items - clear() crashesQGraphicsScene - 删除项目 - clear() 崩溃
【发布时间】:2014-05-09 11:55:20
【问题描述】:

我有一个 QGraphicsScene 和按钮。我想删除那些按钮,但是方法 clear() 不起作用。

mainclass.cpp

MainClass::MainClass(QWidget* parent)
  :QMainWindow(parent)
{
  ui.setupUi(this);
  scene = new QGraphicsScene(this);
  ui.graphicsView->setScene(scene);
  QPixMap picture(":/MainClass/Resources/picture.jpg");
  pixmapItem = scene->addPixmap(picture);
  pixmapItem->setFlag(QGraphicsItem::ItemIsMovable);
}

void MainClass::hideButtons();
{
  scene->clear();
}

也许有办法以不同的方式做到这一点?

函数 hideButtons 被其他函数调用(来自 MainClass 类)。

编辑:好的,我的代码有一些错误,所以我现在知道为什么它不起作用了,但是现在每次我尝试使用以下命令清除场景时它都会崩溃:

scene->clear()

QList<QGraphicsItem*> allGraphicsItems = scene->items();
for(int i = 0; i < allGraphicsItems.size(); i++)
{
  QGraphicsItem *graphicItem = allGraphicsItems[i];
  scene->removeItem(graphicItem);
  delete graphicItem;
  scene->update();
}
qDebug()<<"End of hideButtons()";

如果我用“delete graphicsItem”注释行,它不会崩溃,但项目不会从场景中删除,因为当我尝试读取它们时,我得到:

QGraphicsProxyWidget::setWidget: cannot embed widget 0×5f547d8; already embedded
QGraphicsProxyWidget::setWidget: cannot embed widget 0×5f6a818; already embedded”

我删除的项目没有父项。 有趣的是,程序在写入“End of hideButtons()”后崩溃,所以肯定有一些方法(来自我的类​​之外)试图调用已删除的对象。

【问题讨论】:

    标签: qgraphicsitem


    【解决方案1】:

    我通过不删除按钮解决了这个问题。我重写了我的程序,所以我只隐藏和显示按钮。而且效果很好。

    经过一番思考:我认为更好的解决方案是将 graphicsView 设置为按钮的父级,而不是将该按钮作为小部件添加到场景中。第一个解决方案允许您更简单地更改该按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多