Qt 基础控件 #

控件概览 #

Qt 提供了丰富的控件库,用于构建各种用户界面:

text
┌─────────────────────────────────────────────────────────────┐
│                    Qt 常用控件分类                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  按钮类:                                                   │
│  ├── QPushButton      - 普通按钮                            │
│  ├── QToolButton      - 工具按钮                            │
│  ├── QRadioButton     - 单选按钮                            │
│  └── QCheckBox        - 复选框                              │
│                                                             │
│  输入类:                                                   │
│  ├── QLineEdit        - 单行文本输入                        │
│  ├── QTextEdit        - 多行文本编辑                        │
│  ├── QSpinBox         - 数字输入框                          │
│  ├── QDoubleSpinBox   - 浮点数输入框                        │
│  └── QComboBox        - 下拉选择框                          │
│                                                             │
│  显示类:                                                   │
│  ├── QLabel           - 标签                                │
│  ├── QLCDNumber       - LCD 数字显示                        │
│  ├── QProgressBar     - 进度条                              │
│  └── QStatusBar       - 状态栏                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

QPushButton 按钮 #

基本使用 #

cpp
// 创建按钮
QPushButton *button = new QPushButton("Click Me", this);

// 设置文本
button->setText("New Text");

// 设置图标
button->setIcon(QIcon(":/icons/button.png"));
button->setIconSize(QSize(24, 24));

// 设置大小
button->setFixedSize(100, 30);
button->setMinimumSize(80, 25);

// 设置快捷键
button->setShortcut(QKeySequence("Ctrl+S"));

// 设置为默认按钮
button->setDefault(true);

// 设置为扁平按钮
button->setFlat(true);

// 连接点击信号
connect(button, &QPushButton::clicked, []() {
    qDebug() << "Button clicked";
});

// 带菜单的按钮
QPushButton *menuButton = new QPushButton("Menu", this);
QMenu *menu = new QMenu(this);
menu->addAction("Option 1");
menu->addAction("Option 2");
menu->addSeparator();
menu->addAction("Option 3");
menuButton->setMenu(menu);

按钮样式 #

cpp
// 使用样式表
button->setStyleSheet(R"(
    QPushButton {
        background-color: #3498db;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        font-size: 14px;
    }
    QPushButton:hover {
        background-color: #2980b9;
    }
    QPushButton:pressed {
        background-color: #21618c;
    }
    QPushButton:disabled {
        background-color: #bdc3c7;
    }
)");

QLabel 标签 #

基本使用 #

cpp
// 创建标签
QLabel *label = new QLabel("Hello Qt", this);

// 设置文本
label->setText("New Text");

// 设置对齐方式
label->setAlignment(Qt::AlignCenter);
label->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

// 自动换行
label->setWordWrap(true);

// 设置边距
label->setMargin(10);
label->setIndent(20);

// 文本格式
label->setTextFormat(Qt::PlainText);    // 纯文本
label->setTextFormat(Qt::RichText);     // 富文本
label->setTextFormat(Qt::AutoText);     // 自动检测

// 富文本
label->setText("<b>Bold</b> and <i>italic</i>");
label->setText("<a href='https://qt.io'>Qt Website</a>");
label->setOpenExternalLinks(true);  // 点击链接自动打开

显示图片 #

cpp
// 显示图片
QLabel *imageLabel = new QLabel(this);
QPixmap pixmap(":/images/photo.png");
imageLabel->setPixmap(pixmap);

// 缩放图片
QPixmap scaledPixmap = pixmap.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation);
imageLabel->setPixmap(scaledPixmap);

// 图片适应标签大小
imageLabel->setScaledContents(true);

// 动画
QLabel *animLabel = new QLabel(this);
QMovie *movie = new QMovie(":/images/loading.gif");
animLabel->setMovie(movie);
movie->start();

QLineEdit 单行输入 #

基本使用 #

cpp
// 创建输入框
QLineEdit *lineEdit = new QLineEdit(this);

// 设置文本
lineEdit->setText("Initial text");
lineEdit->setText("");  // 清空

// 获取文本
QString text = lineEdit->text();

// 设置占位符文本
lineEdit->setPlaceholderText("Enter your name...");

// 设置最大长度
lineEdit->setMaxLength(100);

// 设置只读
lineEdit->setReadOnly(true);

// 设置输入掩码
lineEdit->setInputMask("9999-99-99");  // 日期格式
lineEdit->setInputMask("(999) 999-9999");  // 电话号码

// 设置回显模式
lineEdit->setEchoMode(QLineEdit::Normal);        // 正常显示
lineEdit->setEchoMode(QLineEdit::Password);      // 密码模式
lineEdit->setEchoMode(QLineEdit::NoEcho);        // 不显示
lineEdit->setEchoMode(QLineEdit::PasswordEchoOnEdit);  // 编辑时显示

// 设置验证器
QIntValidator *intValidator = new QIntValidator(0, 100, this);
lineEdit->setValidator(intValidator);

QDoubleValidator *doubleValidator = new QDoubleValidator(0.0, 1.0, 2, this);
lineEdit->setValidator(doubleValidator);

QRegularExpressionValidator *regexValidator = new QRegularExpressionValidator(
    QRegularExpression("[A-Za-z]+"), this);
lineEdit->setValidator(regexValidator);

信号与槽 #

cpp
// 文本改变信号
connect(lineEdit, &QLineEdit::textChanged, [](const QString &text) {
    qDebug() << "Text changed:" << text;
});

// 文本编辑完成信号
connect(lineEdit, &QLineEdit::textEdited, [](const QString &text) {
    qDebug() << "Text edited:" << text;
});

// 回车键信号
connect(lineEdit, &QLineEdit::returnPressed, []() {
    qDebug() << "Return pressed";
});

// 光标位置改变信号
connect(lineEdit, &QLineEdit::cursorPositionChanged, [](int oldPos, int newPos) {
    qDebug() << "Cursor moved from" << oldPos << "to" << newPos;
});

清除按钮 #

cpp
// 添加清除按钮
lineEdit->setClearButtonEnabled(true);

// 自定义操作按钮
QAction *clearAction = lineEdit->addAction(
    QIcon(":/icons/clear.png"), QLineEdit::TrailingPosition);
connect(clearAction, &QAction::triggered, lineEdit, &QLineEdit::clear);

QTextEdit 多行文本 #

基本使用 #

cpp
// 创建多行文本编辑器
QTextEdit *textEdit = new QTextEdit(this);

// 设置文本
textEdit->setText("Hello Qt");
textEdit->setPlainText("Plain text");
textEdit->setHtml("<b>Bold</b> text");

// 获取文本
QString text = textEdit->toPlainText();
QString html = textEdit->toHtml();

// 追加文本
textEdit->append("Appended text");

// 清空
textEdit->clear();

// 设置只读
textEdit->setReadOnly(true);

// 自动换行
textEdit->setLineWrapMode(QTextEdit::WidgetWidth);

// 设置字体
textEdit->setFontFamily("Consolas");
textEdit->setFontPointSize(12);

// 设置文字颜色
textEdit->setTextColor(Qt::red);

// 设置背景颜色
textEdit->setTextBackgroundColor(Qt::yellow);

文本格式化 #

cpp
// 获取当前格式
QTextCursor cursor = textEdit->textCursor();
QTextCharFormat format = cursor.charFormat();

// 设置格式
format.setFontWeight(QFont::Bold);
format.setForeground(Qt::red);
format.setBackground(Qt::yellow);
cursor.setCharFormat(format);

// 合并格式
cursor.mergeCharFormat(format);

// 段落格式
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setAlignment(Qt::AlignCenter);
blockFormat.setIndent(2);
cursor.setBlockFormat(blockFormat);

QCheckBox 复选框 #

基本使用 #

cpp
// 创建复选框
QCheckBox *checkBox = new QCheckBox("Enable feature", this);

// 设置选中状态
checkBox->setChecked(true);

// 获取选中状态
bool checked = checkBox->isChecked();

// 三态复选框
checkBox->setTristate(true);  // 启用三态
checkBox->setCheckState(Qt::Unchecked);      // 未选中
checkBox->setCheckState(Qt::PartiallyChecked);  // 部分选中
checkBox->setCheckState(Qt::Checked);        // 选中

// 连接状态改变信号
connect(checkBox, &QCheckBox::stateChanged, [](int state) {
    switch (state) {
        case Qt::Unchecked:
            qDebug() << "Unchecked";
            break;
        case Qt::PartiallyChecked:
            qDebug() << "Partially checked";
            break;
        case Qt::Checked:
            qDebug() << "Checked";
            break;
    }
});

QRadioButton 单选按钮 #

基本使用 #

cpp
// 创建单选按钮
QRadioButton *radio1 = new QRadioButton("Option 1", this);
QRadioButton *radio2 = new QRadioButton("Option 2", this);
QRadioButton *radio3 = new QRadioButton("Option 3", this);

// 设置默认选中
radio1->setChecked(true);

// 分组(使用 QButtonGroup)
QButtonGroup *group = new QButtonGroup(this);
group->addButton(radio1, 1);
group->addButton(radio2, 2);
group->addButton(radio3, 3);

// 获取选中的按钮
int checkedId = group->checkedId();
QAbstractButton *checkedButton = group->checkedButton();

// 连接信号
connect(group, QOverload<int>::of(&QButtonGroup::buttonClicked), [](int id) {
    qDebug() << "Selected option:" << id;
});

QComboBox 下拉框 #

基本使用 #

cpp
// 创建下拉框
QComboBox *comboBox = new QComboBox(this);

// 添加项目
comboBox->addItem("Item 1");
comboBox->addItem("Item 2");
comboBox->addItem("Item 3");

// 添加带图标的项目
comboBox->addItem(QIcon(":/icons/item.png"), "Item with Icon");

// 添加多个项目
comboBox->addItems(QStringList() << "A" << "B" << "C");

// 插入项目
comboBox->insertItem(0, "First Item");

// 设置当前选中
comboBox->setCurrentIndex(0);
comboBox->setCurrentText("Item 1");

// 获取当前选中
int index = comboBox->currentIndex();
QString text = comboBox->currentText();
QVariant data = comboBox->currentData();

// 设置用户数据
comboBox->addItem("Display Text", QVariant(42));  // 附加数据

// 可编辑
comboBox->setEditable(true);

// 自动补全
comboBox->setCompleter(new QCompleter(comboBox->model(), this));

// 连接信号
connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [](int index) {
    qDebug() << "Selected index:" << index;
});

connect(comboBox, &QComboBox::currentTextChanged, [](const QString &text) {
    qDebug() << "Selected text:" << text;
});

QSpinBox 数字输入框 #

基本使用 #

cpp
// 创建数字输入框
QSpinBox *spinBox = new QSpinBox(this);

// 设置范围
spinBox->setRange(0, 100);

// 设置当前值
spinBox->setValue(50);

// 获取当前值
int value = spinBox->value();

// 设置步长
spinBox->setSingleStep(5);

// 设置前缀和后缀
spinBox->setPrefix("$ ");
spinBox->setSuffix(" kg");

// 设置特殊值文本
spinBox->setSpecialValueText("Auto");  // 最小值时显示

// 设置显示进制
spinBox->setDisplayIntegerBase(16);  // 十六进制

// 连接值改变信号
connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged), [](int value) {
    qDebug() << "Value:" << value;
});

// QDoubleSpinBox 浮点数版本
QDoubleSpinBox *doubleSpinBox = new QDoubleSpinBox(this);
doubleSpinBox->setRange(0.0, 1.0);
doubleSpinBox->setSingleStep(0.1);
doubleSpinBox->setDecimals(2);  // 小数位数

QSlider 滑块 #

基本使用 #

cpp
// 创建滑块
QSlider *slider = new QSlider(Qt::Horizontal, this);  // 水平滑块
QSlider *vSlider = new QSlider(Qt::Vertical, this);   // 垂直滑块

// 设置范围
slider->setRange(0, 100);

// 设置当前值
slider->setValue(50);

// 获取当前值
int value = slider->value();

// 设置步长
slider->setSingleStep(1);
slider->setPageStep(10);

// 设置刻度
slider->setTickPosition(QSlider::TicksBelow);
slider->setTickInterval(10);

// 连接值改变信号
connect(slider, &QSlider::valueChanged, [](int value) {
    qDebug() << "Slider value:" << value;
});

QProgressBar 进度条 #

基本使用 #

cpp
// 创建进度条
QProgressBar *progressBar = new QProgressBar(this);

// 设置范围
progressBar->setRange(0, 100);

// 设置当前值
progressBar->setValue(50);

// 设置文本可见
progressBar->setTextVisible(true);

// 设置文本格式
progressBar->setFormat("%p%");  // 百分比
progressBar->setFormat("%v / %m");  // 当前值 / 最大值

// 设置方向
progressBar->setOrientation(Qt::Horizontal);
progressBar->setOrientation(Qt::Vertical);

// 不确定进度模式
progressBar->setRange(0, 0);  // 范围都为 0 时显示滚动动画

// 更新进度
for (int i = 0; i <= 100; ++i) {
    progressBar->setValue(i);
    QCoreApplication::processEvents();  // 处理事件
    QThread::msleep(50);
}

控件启用与禁用 #

cpp
// 禁用控件
button->setEnabled(false);
lineEdit->setEnabled(false);

// 启用控件
button->setEnabled(true);

// 检查是否启用
bool enabled = button->isEnabled();

// 隐藏控件
button->hide();
button->setVisible(false);

// 显示控件
button->show();
button->setVisible(true);

// 检查是否可见
bool visible = button->isVisible();

下一步 #

现在你已经掌握了基础控件的使用,接下来学习 布局管理,了解如何组织这些控件!

最后更新:2026-03-29