I have a horizontal QSplitter with two widgets. I want to replace the right hand widget with a new one in a way that the proportions the user has set are maintained. Below is a simplified version of the code I currently have:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
splitter = new QSplitter(this);
splitter->setOrientation(Qt::Horizontal);
leftWidget = new QPushButton("left", splitter);
rightWidget = new QPushButton("right", splitter);
splitter->addWidget(leftWidget);
splitter->addWidget(rightWidget);
setCentralWidget(splitter);
}
void MainWindow::swapLayout()
{
QList<int> sizes = splitter->sizes();
rightWidget->deleteLater();
splitter->update();
rightWidget = new QPushButton("new right", splitter);
splitter->addWidget(rightWidget);
splitter->setSizes(sizes);
}
swapLayout() saves the sizes, removes the right widget, adds a new right hand widget and attempts to reset the sizes. However the left hand widget occupies 100% of the space. Without trying to restore the sizes the widgets both take up 50% of the space.
I think the actual order of operations is:
sizes.at(2)
is 0
by default. It caused by the fact that deleteLater()
only schedules deleting, and actual deleting is processed after you exit swapLayout()
method. Try delete rightWidget;
instead of rightWidget->deleteLater();
if it possible. Or process events between deleting rightWidget
and adding new one.