Reputation: 539
We have a dynamic dialog that we need to reconfigure depending on user selections. Upon receiving certain signals (selection changes and such), we have to remove all items from a QFormLayout and repopulate it again.
We've tried several approaches, but whatever we do, the old widgets remain in place, and a new layout is created on top of that. The old widgets can still be used, so it's not simply a drawing issue.
This happens Qt 5.2.1 on Kubuntu 14.04.
I've reduced it to the following situation:
A QDialog derived class containing only a vertical layout ( mainLayout ). That layout initially contains only an empty form layout ( formLayout ).
And a function to update the layout. For simplicity it always uses QLineEdit.
Version 1:
void Dialog::replaceFields( const QVector< QString > & names )
{
ui->formLayout->deleteLater() ;
ui->formLayout = new QFormLayout ;
ui->mainLayout->addLayout( ui->formLayout ) ;
for( const QString & name : names )
ui->formLayout->addRow( name, new QLineEdit ) ;
}
Version 2:
void Dialog::replaceFields( const QVector< QString > & names )
{
while( QLayoutItem * item { ui->formLayout->takeAt( 0 ) } )
delete item ;
for( const QString & name : names )
ui->formLayout->addRow( name, new QLineEdit ) ;
}
Both versions give the same result.
Just to clarify, the amount and type of fields is known only at run time, so we can't create all variants in the editor and just swap them.
Upvotes: 0
Views: 2029
Reputation: 27631
Rather than adding and removing the layout, I suggest you create a QWidget and add the layout with its controls to that widget.
Then you can simply delete the widget and recreate it on the fly, as required.
Upvotes: 4