QSpinBox

main.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
#include <QSpinBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include <qapplication.h>

void setupSpinBoxDemo(QWidget *parent) {
QVBoxLayout *layout = new QVBoxLayout(parent);

// --- 1. 基础年龄选择框 ---
QLabel *label1 = new QLabel("请选择年龄 (0-150):", parent);
QSpinBox *ageBox = new QSpinBox(parent);

// 设置属性
ageBox->setRange(0, 150); // 设置最小值和最大值
ageBox->setValue(18); // 设置初始值
ageBox->setSingleStep(1); // 每次点击上下箭头增减 1
ageBox->setSuffix(" 岁"); // 设置后缀(单位)

// --- 2. 步长较大的调节框 ---
QLabel *label2 = new QLabel("调整亮度 (0-100,步长10):", parent);
QSpinBox *brightBox = new QSpinBox(parent);
brightBox->setRange(0, 100);
brightBox->setSingleStep(10); // 每次跳 10
brightBox->setWrapping(true); // 开启循环:到 100 后再点上,会回到 0

// --- 3. 实时显示数值变化的 Label ---
QLabel *displayLabel = new QLabel("当前值:18", parent);

// --- 4. 信号:valueChanged ---
// 每当数值改变,都会触发此信号
QObject::connect(ageBox, QOverload<int>::of(&QSpinBox::valueChanged), [displayLabel](int newValue) {
displayLabel->setText(QString("当前值:%1").arg(newValue));
});

layout->addWidget(label1);
layout->addWidget(ageBox);
layout->addWidget(label2);
layout->addWidget(brightBox);
layout->addWidget(displayLabel);
layout->addStretch();
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);

QWidget w;
w.setWindowTitle("QLineEdit 深度测试");
w.resize(400, 300);

// 调用我们的函数
setupSpinBoxDemo(&w);

w.show();
return a.exec();
}