Page 1 of 1

[SOLVED] Dynamically changing Widgets in a Layout

Posted: Wed Jan 21, 2015 4:10 pm
by Nava2
I'm trying to dynamically remove widgets from a QWidget and replace them with others.

Unfortunately, QtScript seems to be getting in the way.

The approved way to remove widgets is like so in C++:

Code: Select all

QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0)  {
    ...
    delete child;
}
A little digging shows this version:

Code: Select all

  QLayoutItem* item;
  while ( !items_.isEmpty() && ( (item = items_.takeFirst()) != 0 ) ){
    layout()->removeWidget(item);
    delete item; // It works no matter where the item is
  }

  items_.clear(); // clear the list afterwards.
Which is the way that is necessary since back links within the layout exists.

The problem is that this doesn't translate well to QtScript:

Code: Select all

    var rootLayout = this.widget.layout();

    debugger;
    this.widgets.forEach(function (gb) {
        rootLayout.removeWidget(gb);

        delete gb;
    });

    this.widgets = [];
This does not actually remove the Widget or delete it. The widgets remain persistant on the screen. When drawing new Widgets, they are drawn on top of these ones.

I then tried removing the layout, but that is not possible because of the QSharedPointer being maintained by QtScript.

Code: Select all

var rootLayout = this.widget.layout();
delete rootLayout;
rootLayout = new QVBoxLayout();
this.widget.setLayout(rootLayout); // error Layout still set
Source: http://qt-project.org/doc/qt-4.8/qwidget.html#setLayout

So I'm at a loss as to how to replace widgets inside a single widget if I can't delete the Widget's layout like Qt expects.. :(

Re: Dynamically changing Widgets in a Layout

Posted: Wed Jan 21, 2015 10:50 pm
by Nava2
I also tried QWidget::destroy but that didn't remove them.
snapshot2.png
snapshot2.png (12.11 KiB) Viewed 21281 times

Re: Dynamically changing Widgets in a Layout

Posted: Wed Jan 21, 2015 11:51 pm
by Nava2
Using QObject::destroy() slot made this work.