StackDlg.h
// // Created by simp on 2022/3/29. // #ifndef STACKEDWIDGET_STACKDLG_H #define STACKEDWIDGET_STACKDLG_H #include <QListWidget> #include <QString> #include <QDialog> #include <QStackedWidget> #include <QLabel> class StackDlg :public QDialog{ Q_OBJECT public: explicit StackDlg(QWidget *parent=0); ~StackDlg() override; private: QListWidget *list; QStackedWidget *stack; QLabel *label1; QLabel *label2; QLabel *label3; }; #endif //STACKEDWIDGET_STACKDLG_H
StackDlg.cpp
// // Created by simp on 2022/3/29. // #include "StackDlg.h" #include <QHBoxLayout> StackDlg::StackDlg(QWidget *parent): QDialog(parent) { setWindowTitle(tr("StackedWidget")); list = new QListWidget(this);//新建一个QListWidget控件对象 //新建的QListWidget控件中插入三个条目 作为选择项 list->insertItem(0, tr("Window1")); list->insertItem(1, tr("Window2")); list->insertItem(2, tr("Window3")); //创建三个QLabel标签控件对象,作为堆栈窗体需要显示的三层窗体 label1 = new QLabel(tr("WindowTest1")); label2 = new QLabel(tr("WindowTest2")); label3 = new QLabel(tr("WindowTest3")); //新建一个QStackWidget堆栈窗口对象 stack = new QStackedWidget(this); //将创建的三个label标签控件一次插入到堆栈窗口中 stack->addWidget(label1); stack->addWidget(label2); stack->addWidget(label3); auto *mainLayout = new QHBoxLayout(this); //对整个对话窗体进行布局 mainLayout->setMargin(5);//设置对话窗体之间的边距为5 mainLayout->setSpacing(5);//设定各个控件之间的间距为5 mainLayout->addWidget(list); mainLayout->addWidget(stack,0,Qt::AlignCenter); mainLayout->setStretchFactor(list,1); mainLayout->setStretchFactor(stack,3); connect(list, SIGNAL(currentRowChanged(int)),stack, SLOT(setCurrentIndex(int))); } StackDlg::~StackDlg() { }
main.cpp
#include <QApplication> #include <QDebug> #include "StackDlg.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); StackDlg w; w.show(); return a.exec(); }