问题
QGraphicsScene has an addWidget(QWidget *)
function, but no corresponding removeWidget(QWidget *)
. It has only removeItem(QGraphicsItem *)
.
How do I remove a QWidget?
回答1:
Here's a basic sample, see if it works for you.
QGraphicsScene scene;
QPushButton *button = new QPushButton;
//Add item and obtain QGraphicsProxyWidget
QGraphicsProxyWidget *proxy = scene.addWidget(button);
//Remove item
scene.removeItem(proxy);
Just remember to delete any memory you allocate.
Edit: After OP's comments, maybe this is what you want
//add item
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget;
proxy = scene.addWidget(button);
//remove item
scene.removeItem(button->graphicsProxyWidget());
Again, remember to delete proxy, or use a smart pointer.
回答2:
I have a working solution figured out, but I do have some warnings appearing in the console. Here's a basic approximation of what I'm doing:
QGraphicsScene *scene = new QGraphicsScene();
// Add button
QPushButton button = new QPushButton( "Test", this );
scene->addWidget( button );
// Remove button
QGraphicsProxyWidget *proxy;
proxy = proxy->createProxyForChildWidget( button );
scene_->removeItem( proxy );
delete proxy;
proxy = NULL;
delete button;
button = NULL;
Here are the warnings I see though:
QGraphicsProxyWidget::setWidget: cannot embed widget 0x604a2c8 which is not a toplevel widget, and is not a child of an embedded widget QGraphicsProxyWidget::createProxyForChildWidget: top-level widget not in a QGraphicsScene QGraphicsScene::removeItem: cannot remove 0-item
来源:https://stackoverflow.com/questions/30079899/qgraphicsscene-does-not-have-a-function-to-remove-qwidget