Replace a widget in Qt

12,355

Solution 1

Layout takes care of the widgets placed in the layout, according to the hints given by the widget, so calling setGeometry, then doing addLayout is not useful. Also, adding widget to layout resets it parent, so you setting new widget's parent to ui->w1 is not useful either.

Fortunately, there is QLayout::replaceWidget method! Just use that. Example:

QLineEdit* leAmplitude;
leAmplitude = new QLineEdit;
QLayoutItem *previous = ui->glControls->replaceWidget(ui->w1, leAmplitude);
// possibly assert that previous is ui->w1, or just delete it, or whatever

This method was added as late as in Qt 5.2 it seems, so if you need to support older versions, I can expand this answer to cover how to (try to) do the same manually. But in short, you have to use the right QGridLayout::addWidget overload and make sure relevant properties (including at least sizeHint and sizePolicy) match.

Solution 2

try this, it is works:

QLineEdit* leAmplitude;
leAmplitude = new QLineEdit(ui->w1->parentWidget());
ui->w1->parentWidget()->layout()->replaceWidget(ui->w1, leAmplitude);
ui->w1 = leAmplitude;
Share:
12,355
Łukasz Przeniosło
Author by

Łukasz Przeniosło

I am an experienced electrical and embedded software engineer. When it comes to electronics, coding and cake, I push it to the limits.

Updated on June 09, 2022

Comments

  • Łukasz Przeniosło
    Łukasz Przeniosło almost 2 years

    I have a base class which has some gui items that i have set positions of using the designer in Qt creator. Those items are:

    QWidget* w1;
    QWidget* w2;
    QWidget* w3;
    

    Now in a class that inherits that base class, I would like to "transform" those widgets into lineEdit items, that would keep all the geometrical parameters of that widgets. So I do something like this:

    QLineEdit* leAmplitude;
    leAmplitude = new QLineEdit(ui->w1);
    leAmplitude->setGeometry(ui->w1->geometry());
    ui->glControls->addWidget(leAmplitude);
    

    But the added QLineEdit item doesn't appear in the exact same place as w1 item. Its just added at the bottom of other controls in the QGridLayout glControls. How to make the lineEdit to take all geometric parameters from w1?