Important: Please read the Qt Code of Conduct -

workaround to showing a widget when replacing hidden widget in splitter

  • i have a splitter where i insert widgets which might later need to be replaced.
    when the splitter has a widget which is hidden, then when i replace the widget, the new widget is hidden too (from docs: The geometry of the newly inserted widget will be the same as the widget it replaces. Its visible and collapsed states are also inherited.)

    so i wanna know how i can do the widget replacement to get the newly inserted widget displayed regardless of the previous widget's visibility.

    sample code:

    #include <QSplitter>
    #include <QLineEdit>
    #include <QComboBox>
    #include <QPushButton>
    class WidgetContainer : public QWidget
    	WidgetContainer() : m_pSplitter(new QSplitter(Qt::Horizontal, this))
    	void setWidget(QWidget *widget)
    		if (m_pSplitter->widget(0))
    			m_pSplitter->replaceWidget(0, widget);
    			m_pSplitter->insertWidget(0, widget);
    public slots:
    	void addWidget()
    		setWidget(new QComboBox);
    	QSplitter *m_pSplitter = nullptr;
    int main(int argc, char *argv[])
    	QApplication app(argc, argv);
    	WidgetContainer window;
    	auto pLineEdit = new QLineEdit;
    	pLineEdit->hide(); // note: initial widget is hidden
    	auto pBtn = new QPushButton(&window);
    	QObject::connect(pBtn, &QPushButton::clicked, &window, &WidgetContainer::addWidget);
    	return app.exec();

  • Lifetime Qt Champion


    In that case, why not remove the old one and insert the new one ?

  • @SGaist
    yeah but how do i remove it?
    when i tried to get splitter's layout it was null

  • Lifetime Qt Champion

    My bad, there's indeed no remove method. I was on the wrong page of the documentation.

    One thing you can try is to reparent the widget and then insert the new one.

  • @SGaist
    i don't wanna re-parent cause i don't own the widget.
    i just hided the previous widget and inserted the new one

Log in to reply