简体   繁体   中英

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM