2012-12-03 48 views
0

我有一个非常令人沮丧的问题,试图删除我的应用程序中的qgraphicsitems。我有一个菜单控制器负责将按钮添加到布局并将其添加到场景中。这些按钮都与自定义信号和插槽连接。当我改变状态时,我想删除这个控制器并删除所有这些qgraphicsitems。在QGraphicsScene中从QGraphicsLinearLayout删除QGraphics项目

继承人我如何加入他们在我menu_controller.cpp:

QGraphicsWidget * temp;//this is used during iteration to add to the layout 

    this->layout = new QGraphicsLinearLayout(Qt::Vertical);//q graphics view layout 
    this->menu = new QGraphicsWidget;//holds the layout 


    // initialize the proper buttons 
    (this->game_state->is_logged_in()) ? (this->logged_in()) : (this->not_logged_in());//test whether or not the user is logged in to generate the correct menu 

    // now iterate through each button and add to the layout 
    for (int i = 0, z = this->buttons.size(); i < z; i++) { 

     temp = this->scene->addWidget(this->buttons[i]);//add widget to the scene 
     this->layout->addItem(temp);//add this widget to the layou 
     connect(this->buttons[i], SIGNAL(menu_selection(QString)), this, SLOT(set_menu_option(QString)));//connect the button to this 
    } 

    // set menu layout as the layout and then add the menu to the scene 
    this->menu->setLayout(this->layout); 
    this->position(); 
    this->scene->addItem(this->menu); 

最后,我的析构函数是这样的:

QGraphicsScene * scene = this->game_state->get_scene(); 

    QList<QGraphicsItem *> list = scene->items(); 
    QList<QGraphicsItem *>::Iterator it = list.begin(); 

    for (; it != list.end(); ++it) 
     if (*it) 
      scene->removeItem(*it); 

    for (int i = 0, z = this->buttons.size(); i < z; i++) 
     disconnect(this->buttons[i], 0, 0, 0);//button not connected to anything 

    // for each deletes each place in memory 
    for_each(this->buttons.begin(), this->buttons.end(), utilities::delete_ptr()); 

    delete this->layout;//delete the layout container 
    delete this->menu;//delete the menu 

我从场景中删除每个按钮,断开连接按钮,然后尝试在它们上调用删除。

我每次都会收到一个分段错误。场景项目删除正常,并且断开连接正常工作,但由于某种原因,当我删除项目时,它会引发分段错误并使程序崩溃。

回答

1

我的猜测是你的utilities::delete_ptr()有问题。

但无论如何。如果您要删除发件人或收件人,则无需断开信号。当它们中的一个被删除时,这会自动完成。

也不需要浏览场景中的所有项目列表并删除它们。打电话QGraphicsScene::clear()会做。无论如何,即使你没有必要删除这个场景。

0

感谢您的协助。

导致分段错误的原因是小部件与信号连接,因此需要使用deleteLater()方法删除。

似乎删除一个元素信号发送其他小部件,当发生这种情况时,它找不到一个内存的地方,因此称为一个seg故障..