2012-12-03 46 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故障..