[SOLVED] Dynamically changing Widgets in a Layout

Discussion forum for C++ and script developers who are using the QCAD development platform or who are looking to contribute to QCAD (translations, documentation, etc).

Moderator: andrew

Forum rules

Always indicate your operating system and QCAD version.

Attach drawing files, scripts and screenshots.

Post one question per topic.

Post Reply
Nava2
Junior Member
Posts: 15
Joined: Sun Oct 26, 2014 6:01 pm

[SOLVED] Dynamically changing Widgets in a Layout

Post by Nava2 » Wed Jan 21, 2015 4:10 pm

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.. :(
Last edited by Nava2 on Wed Jan 21, 2015 11:52 pm, edited 1 time in total.

Nava2
Junior Member
Posts: 15
Joined: Sun Oct 26, 2014 6:01 pm

Re: Dynamically changing Widgets in a Layout

Post by Nava2 » Wed Jan 21, 2015 10:50 pm

I also tried QWidget::destroy but that didn't remove them.
snapshot2.png
snapshot2.png (12.11 KiB) Viewed 18697 times

Nava2
Junior Member
Posts: 15
Joined: Sun Oct 26, 2014 6:01 pm

Re: Dynamically changing Widgets in a Layout

Post by Nava2 » Wed Jan 21, 2015 11:51 pm

Using QObject::destroy() slot made this work.

Post Reply

Return to “QCAD Programming, Script Programming and Contributing”