I'm creating an application in Qt that allows users to drag around various "modules" in a QGraphicsView. Whenever one of these modules is selected, it emits a signal which is then picked up by a "ConfigurationWidget" which is a side-panel which should display all of the relevant parameters of the selected module:
class ConfigurationWidget : public QWidget
{
Q_OBJECT
public:
ConfigurationWidget(QWidget *parent) : QWidget(parent) {}
public slots:
void moduleSelected(Module* m)
{
if(layout())
{
while (itsLayout->count()>0)
{
delete itsLayout->takeAt(0);
}
}
delete layout();
itsLayout = new QFormLayout(this);
itsLayout->addRow(QString(tr("Type:")), new QLabel(m->name()));
itsLayout->addRow(QString(tr("Instance:")), new QLabel(m->instanceID()));
// ... Display a whole bunch of other fields that depends on the module
}
};
The problem is that the ConfigurationWidget never actually gets cleared when a module is selected. The new fields are just drawn over the old ones. I've tried various combinations of hide() and show(), invalidate(), update(), etc. to no avail.
What's the correct way to make a widget that can change its fields like this on the fly?
Show activity on this post. This code deletes the layout, all its children and everything inside the layout 'disappears'. qDeleteAll(yourWidget->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly)); delete layout(); This deletes all direct widgets of the widget yourWidget .
Once you have add your layout with at least one widget in it, select your window and click the "Update" button of QtDesigner. The interface will be resized at the most optimized size and your layout will fit the whole window. Then when resizing the window, the layout will be resized in the same way.
As prasad_N said, use deleteLater() if you do it inside the widget. If you need to delete the current widget before you create the new one, then you need to emit a signal, connect it to some slot using a Qt::QueuedConnection and in the slot first delete the current widget, then create the new one.
QVBoxLayout organizes your widgets vertically in a window. Instead of organizing all the widgets yourself (specifying the geographic location), you can let PyQt take care of it. Every new widget you add with . addWidget() , is added vertically. Basically you get a vertical list of your widgets.
The code loop I've used before is as follows:
void clearLayout(QLayout *layout) {
if (layout == NULL)
return;
QLayoutItem *item;
while((item = layout->takeAt(0))) {
if (item->layout()) {
clearLayout(item->layout());
delete item->layout();
}
if (item->widget()) {
delete item->widget();
}
delete item;
}
}
Hopefully that will be helpful to you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With