QStackedWidget控件相当于一个容器,提供一个空间来存放一系列的控件,并且每次只能有一个控件是可见的,即被设置为当前的控件。QStackedWidget可用于创建类似于QTabWidget提供的用户界面。 它是一个构建在QStackedLayout类之上的方便布局小部件。

#pragma once
#include
#include "ui_stackedwidget.h"
#include "common/stylemgr.h"class StackedWidget : public QWidget
{Q_OBJECT
private:Ui_stackedwidget *ui;QWidget *aqwidget = nullptr;public:StackedWidget(QWidget *parent = nullptr);~StackedWidget();public slots:void AddAWidget();void ShowAWidget();void DelAWidget();void ShowIndex0();void ShowCurrentChanged(int index);void ShowWidgetRemoved(int index);
};
#include "stackedwidget.h"StackedWidget::StackedWidget(QWidget *parent) : QWidget(parent), ui(new Ui_stackedwidget())
{ui->setupUi(this);StyleMgr::SetStyleToWidgetByCssFile(this, ":/helloqt/resources/qss/custom/stackedwidget.qss");QStringList list;list << "one page"<< "two page"<< "third page";ui->stackedwidget_comboBox->addItems(list);connect(ui->stackedwidget_comboBox, QOverload::of(&QComboBox::activated), ui->stackedwidget_stackedWidget, &QStackedWidget::setCurrentIndex);connect(ui->stackedwidget_stackedWidget, QOverload::of(&QStackedWidget::currentChanged), this, ShowCurrentChanged);connect(ui->stackedwidget_stackedWidget, QOverload::of(&QStackedWidget::widgetRemoved), this, ShowWidgetRemoved);connect(ui->stackedwidget_pushButton_1, &QPushButton::clicked, this, AddAWidget);connect(ui->stackedwidget_pushButton_2, &QPushButton::clicked, this, ShowAWidget);connect(ui->stackedwidget_pushButton_3, &QPushButton::clicked, this, DelAWidget);connect(ui->stackedwidget_pushButton_4, &QPushButton::clicked, this, ShowIndex0);
}StackedWidget::~StackedWidget()
{delete ui;
}void StackedWidget::AddAWidget()
{if (aqwidget == nullptr){aqwidget = new QWidget(ui->stackedwidget_stackedWidget);aqwidget->setObjectName("stackedwidget_page_a");}int index = ui->stackedwidget_stackedWidget->indexOf(aqwidget);qDebug() << index;if (index < 0){ui->stackedwidget_stackedWidget->addWidget(aqwidget);}
}void StackedWidget::ShowAWidget()
{if (aqwidget != nullptr){ui->stackedwidget_stackedWidget->setCurrentWidget(aqwidget);}
}void StackedWidget::DelAWidget()
{if (aqwidget != nullptr){ui->stackedwidget_stackedWidget->removeWidget(aqwidget);}
}void StackedWidget::ShowIndex0()
{ui->stackedwidget_stackedWidget->setCurrentIndex(0);
}void StackedWidget::ShowCurrentChanged(int index)
{QMessageBox msgBox;msgBox.setText(QString("ShowCurrentChanged index %1").arg(index));msgBox.exec();
}void StackedWidget::ShowWidgetRemoved(int index)
{QMessageBox msgBox;msgBox.setText(QString("ShowWidgetRemoved index %1").arg(index));msgBox.exec();
}


https://github.com/weichangk/helloqt
https://doc.qt.io/qt-5/qstackedwidget.html