godzsa
godzsa

Reputation: 2395

Change layout content with pointers in Qt

Is it possible to change the content of a layout with pointers?

I want to do something like the following.

In the header:

QWidget* activeView;
QWidget* one;
QWidget* two;
...

In the source file I set up the Widgets in the constructor, and push the first to the layout:

activeView = one;
ui->activeLayout->addWidget(activeView);

And later with slots or methods I want to change the activeView:

activeView = two;

I tried this, but it won't work. I even called the update() method of the layout.

Upvotes: 0

Views: 370

Answers (1)

Mr. Developerdude
Mr. Developerdude

Reputation: 9678

This will not work unfortunately.

What you want is QStackedWidget. Official documentation is here.

If you don't want to use this widget and want to do it manually, you will have to reconstruct the layout by yourself in code. It can be wrapped in a method and won't be too ugly.

Example:

void clearLayout(QLayout *layout) 
{
    if (layout) {
        while(layout->count() > 0){
            QLayoutItem *item = layout->takeAt(0);
            delete item->widget();
            delete item;
        }
    }
}

void setNewWidgetVisible(QWidget *activeView)
{
   clearLayout(ui->activeLayout);
   ui->activeLayout->addWidget(activeView);
}

Upvotes: 3

Related Questions