堆栈窗口可以根据选择项的不同显示不同的窗体
- // stackeddlg.h
- #ifndef STACKEDDLG_H
- #define STACKEDDLG_H
- #include <QDialog>
- #include <QLabel>
- #include <QListWidget>
- #include <QStackedWidget>
- class StackedDlg : public QDialog
- {
- Q_OBJECT
- public:
- explicit StackedDlg(QWidget *parent = 0);
- signals:
- public slots:
- private:
- QLabel *textLabel;
- QLabel *showLabel;
- QLabel *aboutLabel;
- QListWidget *list;
- QStackedWidget *stack;
- };
- #endif // STACKEDDLG_H
- //stackeddlg.cpp
- #include "stackeddlg.h"
- #include <QHBoxLayout>
- StackedDlg::StackedDlg(QWidget *parent) :
- QDialog(parent)
- {
- //创建一个QListWidget控件 并向其中添加列表项
- list = new QListWidget();
- list->insertItem(0, tr("文本窗口"));
- list->insertItem(1, tr("显示窗口"));
- list->insertItem(2, tr("关于窗口"));
- textLabel = new QLabel(tr("学习使用堆栈窗口"));
- showLabel = new QLabel(tr("仅仅是一个示例程序"));
- aboutLabel = new QLabel(tr("欢迎交流,共同学习"));
- //创建QStackedwidget控件
- stack = new QStackedWidget();
- //将控件添加到堆栈窗口中
- stack->addWidget(textLabel);
- stack->addWidget(showLabel);
- stack->addWidget(aboutLabel);
- //使用一个水平布局管理器对对话框进行布局
- QHBoxLayout *mainLayout = new QHBoxLayout(this);
- mainLayout->addWidget(list);
- mainLayout->addWidget(stack, 0, Qt::AlignHCenter);
- //设置mainLayout的边框与对话框边缘的距离
- mainLayout->setMargin(5);
- mainLayout->setSpacing(5);
- //信号与槽的连接,实现按选择显示窗体
- //此处堆栈窗口的index按插入的顺序从0依次排序,与QListWidget的条目排序一致
- connect(list, SIGNAL(currentRowChanged(int)), stack, SLOT(setCurrentIndex(int)));
- this->setWindowTitle(tr("堆栈窗口"));
- }
- //main.cpp
- #include <QApplication>
- #include <QTextCodec>
- #include "stackeddlg.h"
- int main(int argc, char *argv[])
- {
- QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
- QApplication app(argc, argv);
- StackedDlg dlg;
- dlg.show();
- return app.exec();
- }