2015-07-21 175 views
0

我們有一個QWidget這是由addWidget添加到場景。我們希望在切換到不同的場景時保持顯示。我們的方法是通過removeItem將其暫時從場景中移除,並在切換到另一場景後,我們呼叫addWidget重新添加它。然而,第二addWidget引發錯誤:QWidget的通過的removeItem場景中刪除無法重新添加到另一個場景

QGraphicsProxyWidget::setWidget: cannot embed widget 0x7835ec8; already embedded 

錯誤可以通過下面的代碼被複制:

QWidget *widget = new QWidget; 
scene->addWidget(widget); 
scene->removeItem(widget->graphicsProxyWidget()); 
scene->addWidget(widget); 

似乎removeItem並沒有真正清除深嵌的狀態。有人知道這裏發生了什麼?或者還有其他好的方法來滿足我們的要求嗎?

Qt的版本Qt的是5.3.2。

謝謝!

+0

您的代碼不編譯我。 'removeItem'需要一個'QGraphicsItem',而不是'QGraphicsProxyWidget'。 – jpo38

+0

您需要添加'#include '來傳遞編譯。對不起,我沒有明確提及它。 – wthung

回答

1

你是對的,顯然removeItem不會刪除嵌入的狀態。下面的代碼檢查嵌入狀態是否仍然存在,並使用setWidget手動刪除它。

我建議你報告一個Qt bug,因爲它看起來像一個錯誤(你可以簡單地指出他們到這個職位,我過去做過)。

QGraphicsScene* scene = new QGraphicsScene(); 
QWidget *widget = new QWidget; 
// check widget has no proxy: 
assert(widget->graphicsProxyWidget() == NULL); 
// add the item: 
scene->addWidget(widget); 
// check widget has a proxy attached: 
assert(widget->graphicsProxyWidget() && widget->graphicsProxyWidget()->widget() == widget); 
// remove the item: 
scene->removeItem(widget->graphicsProxyWidget()); 

if (widget->graphicsProxyWidget() && widget->graphicsProxyWidget()->widget() == widget) 
{ 
    // widget still has a proxy attached, is this a Qt bug? 

    // manually unset proxy: 
    widget->graphicsProxyWidget()->setWidget(NULL); 
    // check widget has no proxy: 
    assert(widget->graphicsProxyWidget() == NULL); 
} 
// add the item: 
scene->addWidget(widget); 
// check widget has a proxy attached: 
assert(widget->graphicsProxyWidget() && widget->graphicsProxyWidget()->widget() == widget); 
+0

已報告[Qt bug](https://bugreports.qt.io/browse/QTBUG-47388)。解決方法是在remoteItem之後手動調用'setWidget(NULL)',就像你的代碼一樣。謝謝! – wthung