QStackedWidget

mian.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <QApplication>
#include <QWidget>
#include <QStackedWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>

void setupStackedWidgetDemo(QWidget *parent) {
// 主布局:垂直排列
QVBoxLayout *mainLayout = new QVBoxLayout(parent);

// --- 1. 创建堆栈窗体 ---
QStackedWidget *stackedWidget = new QStackedWidget(parent);

// --- 2. 创建第一页:欢迎页 ---
QWidget *page1 = new QWidget();
QVBoxLayout *layout1 = new QVBoxLayout(page1);
layout1->addWidget(new QLabel("<h3>第一步:欢迎使用安装程序</h3>"));
layout1->addWidget(new QLabel("点击下方按钮开始..."));
layout1->addStretch();

// --- 3. 创建第二页:设置页 ---
QWidget *page2 = new QWidget();
QVBoxLayout *layout2 = new QVBoxLayout(page2);
layout2->addWidget(new QLabel("<h3>第二步:参数配置</h3>"));
layout2->addWidget(new QLabel("请配置您的系统参数。"));
layout2->addStretch();

// --- 4. 创建第三页:完成页 ---
QWidget *page3 = new QWidget();
QVBoxLayout *layout3 = new QVBoxLayout(page3);
layout3->addWidget(new QLabel("<h3>第三步:安装完成!</h3>"));
layout3->addStretch();

// --- 5. 将页面添加到堆栈中 ---
stackedWidget->addWidget(page1);
stackedWidget->addWidget(page2);
stackedWidget->addWidget(page3);

// --- 6. 创建底部控制按钮 ---
QHBoxLayout *btnLayout = new QHBoxLayout();
QPushButton *btnPrev = new QPushButton("上一页");
QPushButton *btnNext = new QPushButton("下一页");
btnLayout->addWidget(btnPrev);
btnLayout->addWidget(btnNext);

// --- 7. 信号处理:切换页面逻辑 ---
QObject::connect(btnNext, &QPushButton::clicked, [stackedWidget]() {
int curr = stackedWidget->currentIndex();
// 如果没到最后一页,就往后跳
if (curr < stackedWidget->count() - 1) {
stackedWidget->setCurrentIndex(curr + 1);
}
});

QObject::connect(btnPrev, &QPushButton::clicked, [stackedWidget]() {
int curr = stackedWidget->currentIndex();
// 如果不是第一页,就往前跳
if (curr > 0) {
stackedWidget->setCurrentIndex(curr - 1);
}
});

// 组装到主布局
mainLayout->addWidget(stackedWidget);
mainLayout->addLayout(btnLayout);
}

int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget w;
w.setWindowTitle("QStackedWidget 向导模式演示");
w.resize(400, 300);
setupStackedWidgetDemo(&w);
w.show();
return a.exec();
}