问题
In my app have a window splitted by a QSplitter, and I need to remove an widget.
How can I do that? I can't find useful methods
回答1:
Many things in Qt cannot be "traditionally" removed. Instead call hide() on it and destruct it. From QSplitter documentation:
When you hide() a child its space will be distributed among the other children. It will be reinstated when you show() it again.
回答2:
It's not clear to me if you want to preserve the widget and put it somewhere else, or if you want to destroy the widget.
Destroying the widget: If you can get a pointer to the widget, you can simply delete it. The splitter will safely be notified that its child is being deleted and will remove it from itself.
Preserving the widget: If you grab the pointer to the widget, you can simply set its parent to some other widget and add it to another widget's layout and it will show up there. This is safe because the QSplitter will be notified that one of its children is being reparented.
If you want to set the parent to NULL (cjhuitt's answer) be aware that you are now responsible for cleaning up that memory because the widget no longer has a parent.
回答3:
I like Tuminoid's answer. But if you absolutely need it removed, try getting the widget you want to remove, and calling setParent( NULL )
on that widget. That's my best guess.
回答4:
If you hold a pointer to the widget, then just delete it, or use deleteLater() if you want to be on the safe side.
If you do not have the widget pointer, use QSplitter::widget(int index) function. Then, you can use invoke its deleteLater() slot.
If you do not have the widget index, but you still know the widget objectName(), then QObject::findChild() is your only way to get the widget pointer.
回答5:
I ran into the same problem. In Qt 4.8 to temporally hide one of the widget of a QSplitter I simply hide it. However it is not enough, as the splitter handle is still available to move. But the handle can be accessed and hidden as well:
frameA->setVisible(conditionA);
frameB->setVisible(conditionB);
if ( !(conditionA && conditionB) ) // if only 1 frame is visible
{
splitter->handle(0)->setVisible(false);
}
回答6:
Another easy way to prevent the child widget from getting deleted is to use QSplitter.takeWidget(child). This is also the recommended way of removing the widget from a splitter. (Qt Documentation)
来源:https://stackoverflow.com/questions/371599/how-to-remove-qwidgets-from-qsplitter