Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a widget in Qt

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?

like image 926
Łukasz Przeniosło Avatar asked Feb 13 '16 16:02

Łukasz Przeniosło


People also ask

How do I replace a widget?

First, tap-and-hold on a widget to grab it. You can see the Remove option displayed at the top of the screen. Move your finger to drag the widget onto Remove. Once you have it there, lift your finger.

How do I add widgets to Qt?

To add widgets in Qt Designer: In the Qt Creator Edit mode, double-click the notepad. ui file in the Projects view to launch the file in the integrated Qt Designer. Drag and drop widgets Text Edit (QTextEdit) to the form.

Should I use Qt Quick or Qt widgets?

Qt Widgets provide means for customization via style sheets, but Qt Quick is a better performing choice for user interfaces that do not aim to look native. Qt Widgets do not scale well for animations. Qt Quick offers a convenient and natural way to implement animations in a declarative manner.


2 Answers

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.

like image 61
hyde Avatar answered Oct 05 '22 22:10

hyde


try this, it is works:

QLineEdit* leAmplitude;
leAmplitude = new QLineEdit(ui->w1->parentWidget());
ui->w1->parentWidget()->layout()->replaceWidget(ui->w1, leAmplitude);
ui->w1 = leAmplitude;
like image 37
indalive Avatar answered Oct 05 '22 22:10

indalive