How to remove QWidgets from QSplitter

拟墨画扇 提交于 2019-12-01 03:15:36
Tuminoid

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.

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.

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.

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.

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);
}

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!