#-------------------------------------------------
#
# Project created by QtCreator 2018-09-26T19:54:31
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = StackedWidget
TEMPLATE = app
SOURCES += main.cpp\
stackdlg.cpp
HEADERS += stackdlg.h
QMAKE_CXXFLAGS += -std=c++11
#ifndef STACKDLG_H
#define STACKDLG_H
#include <QDialog>
class QListWidget;
class QStackedWidget;
class QLabel;
class QHBoxLayout;
class StackDlg : public QDialog
{
Q_OBJECT
public:
StackDlg(QWidget *parent = 0);
~StackDlg();
private:
inline void CreateQListWidget();
inline void CreateQLabels();
inline void CreateQStackedWidgetAndAddQLabels();
inline void CreateMainLayout();
private:
QListWidget *list;
QStackedWidget *stack;
QLabel *label1;
QLabel *label2;
QLabel *label3;
QHBoxLayout *mainLayout;
};
#endif // STACKDLG_H
#include "stackdlg.h"
#include <QListWidget>
#include <QStackedWidget>
#include <QLabel>
#include <QHBoxLayout>
StackDlg::StackDlg(QWidget *parent)
: QDialog(parent), list(nullptr), stack(nullptr)
, label1(nullptr), label2(nullptr), label3(nullptr)
, mainLayout(nullptr)
{
setWindowTitle(tr("StackedWidget"));
CreateMainLayout();
}
void StackDlg::CreateQListWidget()
{
if (!list)
list = new QListWidget(this);
list->insertItem(0, tr("Window1"));
list->insertItem(1, tr("Window2"));
list->insertItem(2, tr("Window3"));
}
void StackDlg::CreateQLabels()
{
if (!label1)
label1 = new QLabel(tr("WindowTest1"));
if (!label2)
label2 = new QLabel(tr("WindowTest2"));
if (!label3)
label3 = new QLabel(tr("WindowTest3"));
}
void StackDlg::CreateQStackedWidgetAndAddQLabels()
{
if (!stack)
stack = new QStackedWidget(this);
CreateQLabels();
stack->addWidget(label1);
stack->addWidget(label2);
stack->addWidget(label3);
}
void StackDlg::CreateMainLayout()
{
if (!mainLayout)
mainLayout = new QHBoxLayout(this);
mainLayout->setMargin(5);
mainLayout->setSpacing(5);
CreateQListWidget();
mainLayout->addWidget(list);
CreateQStackedWidgetAndAddQLabels();
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()
{
if (list) delete list;
if (label1) delete label1;
if (label2) delete label2;
if (label3) delete label3;
if (stack) delete stack;
if (mainLayout) delete mainLayout;
}
输出结果: