【QT】常用控件全攻略:从入门到精通,打造炫酷GUI!

Qt界面开发30+核心控件全攻略

在这里插入图片描述

个人主页:Guiat
归属专栏:QT

在这里插入图片描述

正文

10大类别、30+核心控件详解,附150+代码示例和交互图表,轻松掌握Qt界面开发精髓!

1. 按钮类控件:用户交互的第一道门

1.1 QPushButton:万能按钮

功能:最常用的按钮控件,支持文本、图标、快捷键等丰富功能

经典场景

// 创建带图标的按钮
QPushButton *downloadBtn = new QPushButton(QIcon(":/icons/download.png"), "下载");
downloadBtn->setToolTip("点击下载最新版本");
connect(downloadBtn, &QPushButton::clicked, [](){
    qDebug() << "开始下载文件...";
    // 实际下载逻辑
});

属性设置技巧

// 设置按钮样式
downloadBtn->setStyleSheet(
    "QPushButton { background-color: #4CAF50; color: white; border-radius: 5px; }"
    "QPushButton:hover { background-color: #45a049; }"
    "QPushButton:pressed { background-color: #3d8b40; }"
);

1.2 QRadioButton:单选之王

使用场景:性别选择、考试单选题、设置选项等需要互斥选择的场景

性别选择
用户选择男
用户选择女
禁用女选项
禁用男选项

代码实现

QButtonGroup *genderGroup = new QButtonGroup;

QRadioButton *maleBtn = new QRadioButton("男");
QRadioButton *femaleBtn = new QRadioButton("女");

genderGroup->addButton(maleBtn, 0);
genderGroup->addButton(femaleBtn, 1);

// 设置默认选择
maleBtn->setChecked(true);

// 获取选择结果
int selectedId = genderGroup->checkedId();

1.3 QCheckBox:多选专家

特殊功能:支持三态复选框(选中/未选中/部分选中)

// 创建三态复选框
QCheckBox *agreeCheck = new QCheckBox("同意用户协议");
agreeCheck->setTristate(true);  // 启用三态

// 状态变化处理
connect(agreeCheck, &QCheckBox::stateChanged, [](int state){
    switch(state) {
        case Qt::Unchecked:
            qDebug() << "未同意协议";
            break;
        case Qt::PartiallyChecked:
            qDebug() << "部分同意条款";
            break;
        case Qt::Checked:
            qDebug() << "已同意全部协议";
            break;
    }
});

2. 文本类控件:信息展示的核心

2.1 QLabel:全能文本展示

高级用法:富文本显示、可点击链接、图片展示

// 创建多功能标签
QLabel *infoLabel = new QLabel;
infoLabel->setTextFormat(Qt::RichText);
infoLabel->setText("<h2>欢迎使用QT助手</h2>"
                   "<p>点击<a href='https://www.qt.io'>这里</a>访问官网</p>"
                   "<img src=':/images/logo.png' width='100'>");

// 链接点击事件
connect(infoLabel, &QLabel::linkActivated, [](const QString &link){
    QDesktopServices::openUrl(QUrl(link));
});

2.2 QTextEdit:富文本编辑器

核心功能:支持HTML格式、语法高亮、文本查找替换

QTextEdit
+setHtml(QString)
+toHtml() : QString
+find(QString) : bool
+append(QString)
+setFontWeight(int)
+setTextColor(QColor)
+insertImage(QString)
QWidget

代码示例

// 创建富文本编辑器
QTextEdit *editor = new QTextEdit;
editor->setHtml("<b>粗体文本</b> <i>斜体文本</i> <u>下划线</u>");

// 插入图片
editor->textCursor().insertImage(":/images/screenshot.png");

// 实现查找功能
QLineEdit *searchInput = new QLineEdit;
QPushButton *searchBtn = new QPushButton("查找");
connect(searchBtn, &QPushButton::clicked, [=](){
    bool found = editor->find(searchInput->text());
    if(!found) QMessageBox::information(this, "查找", "未找到匹配内容");
});

2.3 QLineEdit:单行输入神器

实用特性:输入验证、密码模式、自动补全

QLineEdit *usernameInput = new QLineEdit;
usernameInput->setPlaceholderText("请输入用户名");

// 设置输入验证器(只允许字母和数字)
QRegularExpressionValidator *validator = new QRegularExpressionValidator(
    QRegularExpression("[a-zA-Z0-9]{4,12}"), this);
usernameInput->setValidator(validator);

// 密码输入框
QLineEdit *passwordInput = new QLineEdit;
passwordInput->setEchoMode(QLineEdit::Password);
passwordInput->setPlaceholderText("请输入密码");

// 添加显示密码按钮
QAction *showPassword = passwordInput->addAction(
    QIcon(":/icons/eye.png"), QLineEdit::TrailingPosition);
showPassword->setCheckable(true);
connect(showPassword, &QAction::toggled, [passwordInput](bool checked){
    passwordInput->setEchoMode(checked ? 
        QLineEdit::Normal : QLineEdit::Password);
});

3. 列表类控件:数据展示专家

3.1 QListWidget:简单列表

适用场景:文件列表、联系人列表、消息记录

// 创建带图标的列表
QListWidget *fileList = new QListWidget;
QListWidgetItem *item1 = new QListWidgetItem(
    QIcon(":/icons/file.png"), "项目计划书.docx");
QListWidgetItem *item2 = new QListWidgetItem(
    QIcon(":/icons/image.png"), "产品截图.jpg");

fileList->addItem(item1);
fileList->addItem(item2);

// 添加右键菜单
fileList->setContextMenuPolicy(Qt::CustomContextMenu);
connect(fileList, &QListWidget::customContextMenuRequested, 
        [=](const QPoint &pos){
    QMenu menu;
    QAction *openAction = menu.addAction("打开");
    QAction *deleteAction = menu.addAction("删除");
    
    QAction *selected = menu.exec(fileList->mapToGlobal(pos));
    if(selected == openAction) {
        // 打开文件逻辑
    } else if(selected == deleteAction) {
        delete fileList->currentItem();
    }
});

3.2 QComboBox:下拉选择器

高级用法:可编辑下拉框、动态数据加载、自定义视图

选择有效
选择无效
用户点击下拉按钮
显示选项列表
用户选择选项
更新当前显示
保持原值
触发currentIndexChanged信号

代码示例

QComboBox *cityCombo = new QComboBox;
cityCombo->setEditable(true);  // 可编辑
cityCombo->addItem("北京");
cityCombo->addItem("上海");
cityCombo->addItem("广州");
cityCombo->addItem("深圳");

// 设置自动补全
QCompleter *completer = new QCompleter(cityCombo->model());
completer->setFilterMode(Qt::MatchContains);
cityCombo->setCompleter(completer);

// 响应选择变化
connect(cityCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
        [](int index){
    qDebug() << "选择了城市:" << cityCombo->itemText(index);
});

3.3 QTreeWidget:树形结构

使用场景:文件浏览器、组织结构图、分类目录

// 创建文件系统树
QTreeWidget *fileTree = new QTreeWidget;
fileTree->setHeaderLabels({"名称", "类型", "修改日期"});

QTreeWidgetItem *rootItem = new QTreeWidgetItem({"本地磁盘(C:)", "磁盘", ""});
QTreeWidgetItem *docsItem = new QTreeWidgetItem({"我的文档", "文件夹", "2023-06-01"});
QTreeWidgetItem *imgItem = new QTreeWidgetItem({"图片", "文件夹", "2023-05-15"});

// 构建层次结构
fileTree->addTopLevelItem(rootItem);
rootItem->addChild(docsItem);
rootItem->addChild(imgItem);

// 添加文件节点
docsItem->addChild(new QTreeWidgetItem({"报告.doc", "Word文档", "2023-06-10"}));
imgItem->addChild(new QTreeWidgetItem({"头像.jpg", "JPEG图像", "2023-05-20"}));

// 展开所有节点
fileTree->expandAll();

// 添加双击打开功能
connect(fileTree, &QTreeWidget::itemDoubleClicked, [](QTreeWidgetItem *item, int column){
    if(item->childCount() == 0) {  // 是文件
        QMessageBox::information(nullptr, "打开文件", "打开: " + item->text(0));
    }
});

4. 进度与滑块:可视化操作

4.1 QProgressBar:进度展示

创意用法:自定义样式、动态效果、多状态显示

QProgressBar *progressBar = new QProgressBar;
progressBar->setRange(0, 100);
progressBar->setValue(0);

// 自定义样式
progressBar->setStyleSheet(
    "QProgressBar {"
    "   border: 2px solid grey;"
    "   border-radius: 5px;"
    "   text-align: center;"
    "}"
    "QProgressBar::chunk {"
    "   background-color: #05B8CC;"
    "   width: 10px;"  // 块状效果
    "}"
);

// 模拟进度更新
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [progressBar](){
    int val = progressBar->value() + 5;
    if(val > 100) val = 0;
    progressBar->setValue(val);
});
timer->start(500);

4.2 QSlider:滑动选择

实用技巧:双向滑块、刻度标记、自定义手柄

QSlider *volumeSlider = new QSlider(Qt::Horizontal);
volumeSlider->setRange(0, 100);
volumeSlider->setValue(50);
volumeSlider->setTickPosition(QSlider::TicksBelow);
volumeSlider->setTickInterval(10);

// 自定义滑块样式
volumeSlider->setStyleSheet(
    "QSlider::groove:horizontal {"
    "    height: 8px;"
    "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
    "        stop:0 #B1B1B1, stop:1 #D9D9D9);"
    "    margin: 2px 0;"
    "}"
    "QSlider::handle:horizontal {"
    "    background: #05B8CC;"
    "    width: 18px;"
    "    margin: -8px 0;"
    "    border-radius: 9px;"
    "}"
);

// 添加音量图标
QLabel *volumeIcon = new QLabel;
volumeIcon->setPixmap(QPixmap(":/icons/volume.png").scaled(24,24));

4.3 QDial:旋钮控制器

适用场景:音量调节、参数微调、模拟仪表盘

graph TD
    A[用户旋转QDial] --> B[值改变事件]
    B --> C[更新关联控件]
    C --> D[执行相关操作]
    D --> E[例如:调节音量/亮度]

代码实现

// 创建旋钮和关联标签
QDial *brightnessDial = new QDial;
brightnessDial->setRange(0, 100);
brightnessDial->setValue(70);
brightnessDial->setNotchesVisible(true);

QLabel *valueLabel = new QLabel;
valueLabel->setAlignment(Qt::AlignCenter);

// 实时显示值
connect(brightnessDial, &QDial::valueChanged, [valueLabel](int value){
    valueLabel->setText(QString("亮度: %1%").arg(value));
    // 实际调整亮度逻辑
    adjustScreenBrightness(value);
});

// 添加视觉效果
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect;
effect->setBlurRadius(15);
effect->setOffset(3, 3);
brightnessDial->setGraphicsEffect(effect);

5. 容器类控件:界面组织大师

5.1 QTabWidget:选项卡容器

高级功能:可关闭标签、自定义标签栏、拖拽排序

QTabWidget *tabWidget = new QTabWidget;

// 添加三个标签页
tabWidget->addTab(new QTextEdit, "文档");
tabWidget->addTab(new QListWidget, "任务");
tabWidget->addTab(new QTreeWidget, "文件");

// 设置标签可关闭
tabWidget->setTabsClosable(true);
connect(tabWidget, &QTabWidget::tabCloseRequested, 
        [tabWidget](int index){ tabWidget->removeTab(index); });

// 自定义标签样式
tabWidget->setStyleSheet(
    "QTabWidget::pane { border: 1px solid #C4C4C4; }"
    "QTabBar::tab {"
    "    background: #F0F0F0;"
    "    padding: 8px 15px;"
    "    border: 1px solid #C4C4C4;"
    "    border-bottom: none;"
    "    border-top-left-radius: 4px;"
    "    border-top-right-radius: 4px;"
    "}"
    "QTabBar::tab:selected {"
    "    background: white;"
    "    margin-bottom: -1px;"  // 覆盖底部边框
    "}"
);

5.2 QGroupBox:分组容器

使用场景:设置分组、表单分组、选项分类

// 创建用户信息分组
QGroupBox *userGroup = new QGroupBox("用户信息");
userGroup->setCheckable(true);
userGroup->setChecked(true);

// 组内布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(new QLabel("姓名:"));
layout->addWidget(new QLineEdit);
layout->addWidget(new QLabel("邮箱:"));
layout->addWidget(new QLineEdit);
userGroup->setLayout(layout);

// 启用/禁用整个分组
connect(userGroup, &QGroupBox::toggled, [userGroup](bool checked){
    QList<QWidget*> children = userGroup->findChildren<QWidget*>();
    for(QWidget *child : children) {
        child->setEnabled(checked);
    }
});

5.3 QStackedWidget:堆叠容器

适用场景:向导界面、多步骤表单、配置页面切换

用户 导航栏 QStackedWidget 当前页面 新页面 点击"下一步" setCurrentIndex(next) hide() show() 显示新内容 用户 导航栏 QStackedWidget 当前页面 新页面

代码实现

QStackedWidget *stack = new QStackedWidget;

// 添加三个页面
QWidget *page1 = createWelcomePage();
QWidget *page2 = createFormPage();
QWidget *page3 = createSummaryPage();
stack->addWidget(page1);
stack->addWidget(page2);
stack->addWidget(page3);

// 导航按钮
QPushButton *backBtn = new QPushButton("上一步");
QPushButton *nextBtn = new QPushButton("下一步");

// 导航逻辑
connect(nextBtn, &QPushButton::clicked, [stack](){
    if(stack->currentIndex() < stack->count()-1) {
        stack->setCurrentIndex(stack->currentIndex() + 1);
    }
});
connect(backBtn, &QPushButton::clicked, [stack](){
    if(stack->currentIndex() > 0) {
        stack->setCurrentIndex(stack->currentIndex() - 1);
    }
});

6. 对话框类:用户沟通桥梁

6.1 QMessageBox:消息弹窗

完整用法:多种图标、自定义按钮、详细文本

// 自定义消息对话框
QMessageBox msgBox;
msgBox.setWindowTitle("软件更新");
msgBox.setText("发现新版本 2.0.1");
msgBox.setInformativeText("是否立即下载更新?");
msgBox.setDetailedText("更新内容:\n1. 修复已知问题\n2. 优化性能\n3. 新增暗黑模式");

// 添加自定义按钮
QPushButton *downloadBtn = msgBox.addButton("下载", QMessageBox::ActionRole);
QPushButton *laterBtn = msgBox.addButton("稍后提醒", QMessageBox::RejectRole);
QPushButton *ignoreBtn = msgBox.addButton("忽略此版本", QMessageBox::DestructiveRole);

msgBox.setIconPixmap(QPixmap(":/icons/update.png").scaled(64,64));

if(msgBox.exec() == QMessageBox::Accepted) {
    // 处理下载逻辑
} else if(msgBox.clickedButton() == laterBtn) {
    // 设置稍后提醒
} else if(msgBox.clickedButton() == ignoreBtn) {
    // 标记此版本为忽略
}

6.2 QFileDialog:文件对话框

高级技巧:自定义过滤器、多选模式、预览功能

// 创建带预览的文件对话框
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::ExistingFiles);
dialog.setNameFilter("图片 (*.png *.jpg *.jpeg);;所有文件 (*)");

// 添加预览面板
QLabel *preview = new QLabel;
preview->setFixedSize(200, 200);
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.layout()->addWidget(preview);

// 预览逻辑
connect(&dialog, &QFileDialog::currentChanged, [preview](const QString &path){
    if(QFileInfo(path).isFile()) {
        QPixmap pix(path);
        if(!pix.isNull()) {
            preview->setPixmap(pix.scaled(preview->size(), 
                Qt::KeepAspectRatio, Qt::SmoothTransformation));
            return;
        }
    }
    preview->clear();
});

if(dialog.exec()) {
    qDebug() << "已选择文件:" << dialog.selectedFiles();
}

6.3 QInputDialog:输入对话框

使用场景:快速获取用户输入、数字选择、下拉选择

// 多种输入方式示例
bool ok;

// 文本输入
QString name = QInputDialog::getText(this, "输入姓名", "姓名:", 
                    QLineEdit::Normal, "", &ok);
if(ok && !name.isEmpty()) { /* 处理 */ }

// 数字输入
int age = QInputDialog::getInt(this, "输入年龄", "年龄:", 
                    20, 0, 120, 1, &ok);
if(ok) { /* 处理 */ }

// 下拉选择
QStringList items = {"初级", "中级", "高级"};
QString level = QInputDialog::getItem(this, "选择级别", "技能级别:", 
                    items, 0, false, &ok);
if(ok) { /* 处理 */ }

7. 菜单与工具栏:专业级界面

7.1 QMenu:右键菜单

高级特性:子菜单、图标菜单、动态菜单

// 创建带图标的右键菜单
QMenu *contextMenu = new QMenu;

QAction *copyAction = contextMenu->addAction(
    QIcon(":/icons/copy.png"), "复制");
QAction *pasteAction = contextMenu->addAction(
    QIcon(":/icons/paste.png"), "粘贴");
contextMenu->addSeparator();

// 添加子菜单
QMenu *formatMenu = contextMenu->addMenu("格式");
formatMenu->addAction("加粗");
formatMenu->addAction("斜体");
formatMenu->addAction("下划线");

// 连接信号
connect(copyAction, &QAction::triggered, [](){ qDebug() << "复制操作"; });
connect(pasteAction, &QAction::triggered, [](){ qDebug() << "粘贴操作"; });

// 在控件上使用
textEdit->setContextMenuPolicy(Qt::CustomContextMenu);
connect(textEdit, &QTextEdit::customContextMenuRequested,
        [=](const QPoint &pos){ contextMenu->exec(textEdit->mapToGlobal(pos)); });

7.2 QToolBar:工具栏

实用技巧:可浮动、可移动、添加自定义控件

// 创建主工具栏
QToolBar *mainToolbar = addToolBar("主工具栏");
mainToolbar->setMovable(true);
mainToolbar->setFloatable(true);

// 添加工具按钮
mainToolbar->addAction(QIcon(":/icons/new.png"), "新建");
mainToolbar->addAction(QIcon(":/icons/open.png"), "打开");
mainToolbar->addSeparator();
mainToolbar->addAction(QIcon(":/icons/save.png"), "保存");

// 添加自定义控件(搜索框)
QLineEdit *searchBox = new QLineEdit;
searchBox->setPlaceholderText("搜索...");
mainToolbar->addWidget(searchBox);

// 添加下拉菜单
QToolButton *formatBtn = new QToolButton;
formatBtn->setIcon(QIcon(":/icons/format.png"));
formatBtn->setPopupMode(QToolButton::InstantPopup);

QMenu *formatMenu = new QMenu;
formatMenu->addAction("加粗");
formatMenu->addAction("斜体");
formatBtn->setMenu(formatMenu);
mainToolbar->addWidget(formatBtn);

7.3 QStatusBar:状态栏

实用功能:临时消息、永久信息、进度指示

// 配置状态栏
QStatusBar *statusBar = new QStatusBar;

// 添加常规标签
QLabel *modeLabel = new QLabel("普通模式");
statusBar->addWidget(modeLabel);

// 添加永久信息(右侧)
QLabel *lineLabel = new QLabel("行: 1");
QLabel *colLabel = new QLabel("列: 1");
statusBar->addPermanentWidget(lineLabel);
statusBar->addPermanentWidget(colLabel);

// 显示临时消息
statusBar->showMessage("就绪", 3000);  // 显示3秒

// 添加进度条
QProgressBar *progress = new QProgressBar;
progress->setMaximumWidth(150);
progress->setRange(0, 100);
progress->setVisible(false);
statusBar->addPermanentWidget(progress);

// 在长时间操作时显示进度
connect(this, &MainWindow::operationStarted, [progress](){
    progress->setVisible(true);
    progress->setValue(0);
});

connect(this, &MainWindow::operationProgress, progress, &QProgressBar::setValue);

connect(this, &MainWindow::operationFinished, [progress](){
    progress->setVisible(false);
});

8. 高级控件:提升用户体验

8.1 QCalendarWidget:日历控件

增强功能:日期范围限制、自定义样式、日期标记

QCalendarWidget *calendar = new QCalendarWidget;

// 设置可选范围
calendar->setMinimumDate(QDate::currentDate().addDays(-30));
calendar->setMaximumDate(QDate::currentDate().addDays(365));

// 标记特殊日期
QTextCharFormat holidayFormat;
holidayFormat.setForeground(Qt::red);

QVector<QDate> holidays = {
    QDate::currentDate().addDays(3),
    QDate::currentDate().addDays(10)
};

for(const QDate &date : holidays) {
    calendar->setDateTextFormat(date, holidayFormat);
}

// 自定义样式
calendar->setStyleSheet(
    "QCalendarWidget QToolButton {"
    "   height: 30px;"
    "   font-size: 14px;"
    "}"
    "QCalendarWidget QMenu {"
    "   width: 150px;"
    "}"
);

8.2 QWebEngineView:现代浏览器

应用场景:内嵌网页、展示HTML内容、混合应用开发

// 创建浏览器组件
QWebEngineView *webView = new QWebEngineView;
webView->load(QUrl("https://www.qt.io"));

// 添加开发者工具
QWebEngineView *devTools = new QWebEngineView;
webView->page()->setDevToolsPage(devTools->page());

// 创建浏览器工具栏
QToolBar *webToolbar = new QToolBar("导航");
QAction *backAction = webToolbar->addAction("后退");
QAction *forwardAction = webToolbar->addAction("前进");
QLineEdit *urlBar = new QLineEdit;

// 连接信号
connect(backAction, &QAction::triggered, webView, &QWebEngineView::back);
connect(forwardAction, &QAction::triggered, webView, &QWebEngineView::forward);
connect(urlBar, &QLineEdit::returnPressed, [webView, urlBar](){
    webView->load(QUrl(urlBar->text()));
});
connect(webView, &QWebEngineView::urlChanged, [urlBar](const QUrl &url){
    urlBar->setText(url.toString());
});

8.3 QGraphicsView:图形视图框架

强大功能:2D图形绘制、复杂场景管理、动画效果

QGraphicsScene
管理图形项
QGraphicsItem
矩形/椭圆/文本等
自定义图形项
通过QGraphicsView显示
视图变换
缩放/旋转/平移

简单示例

// 创建图形场景
QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(0, 0, 800, 600);

// 添加图形项
QGraphicsRectItem *rect = scene->addRect(50, 50, 200, 100);
rect->setBrush(QBrush(Qt::blue));

QGraphicsEllipseItem *ellipse = scene->addEllipse(300, 100, 150, 150);
ellipse->setBrush(QBrush(Qt::green));

// 添加可移动文本项
QGraphicsTextItem *text = scene->addText("可拖动文本");
text->setPos(200, 300);
text->setFlag(QGraphicsItem::ItemIsMovable);

// 创建视图
QGraphicsView *view = new QGraphicsView(scene);
view->setRenderHint(QPainter::Antialiasing);

9. 布局管理:界面自动适配

9.1 QHBoxLayout/QVBoxLayout:基础布局

组合技巧:嵌套使用实现复杂界面

// 创建表单布局
QWidget *formWidget = new QWidget;
QVBoxLayout *mainLayout = new QVBoxLayout(formWidget);

// 第一行
QHBoxLayout *row1 = new QHBoxLayout;
row1->addWidget(new QLabel("用户名:"));
row1->addWidget(new QLineEdit);
mainLayout->addLayout(row1);

// 第二行
QHBoxLayout *row2 = new QHBoxLayout;
row2->addWidget(new QLabel("密码:"));
row2->addWidget(new QLineEdit)->setEchoMode(QLineEdit::Password);
mainLayout->addLayout(row2);

// 按钮行
QHBoxLayout *buttonRow = new QHBoxLayout;
buttonRow->addStretch();  // 添加弹性空间
buttonRow->addWidget(new QPushButton("登录"));
buttonRow->addWidget(new QPushButton("取消"));
mainLayout->addLayout(buttonRow);

9.2 QGridLayout:网格布局

适用场景:表单设计、仪表盘、棋盘类界面

// 创建计算器界面
QWidget *calculator = new QWidget;
QGridLayout *grid = new QGridLayout(calculator);

QPushButton *buttons[16];
const QString labels[16] = {
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "0", ".", "=", "+"
};

// 添加按钮
for(int i = 0; i < 4; ++i) {
    for(int j = 0; j < 4; ++j) {
        int index = i*4 + j;
        buttons[index] = new QPushButton(labels[index]);
        grid->addWidget(buttons[index], i, j);
    }
}

// 添加显示框
QLCDNumber *display = new QLCDNumber;
grid->addWidget(display, 0, 0, 1, 4);  // 跨4列

// 设置行列比例
grid->setRowStretch(1, 1);
grid->setRowStretch(2, 1);
grid->setRowStretch(3, 1);
grid->setColumnStretch(0, 1);
grid->setColumnStretch(1, 1);
grid->setColumnStretch(2, 1);
grid->setColumnStretch(3, 1);

9.3 QFormLayout:表单布局

专业技巧:自动标签对齐、添加行、字段类型

// 创建用户注册表单
QWidget *form = new QWidget;
QFormLayout *formLayout = new QFormLayout(form);

// 添加不同字段
formLayout->addRow("用户名:", new QLineEdit);
formLayout->addRow("密码:", new QLineEdit)->setEchoMode(QLineEdit::Password);
formLayout->addRow("邮箱:", new QLineEdit);

// 添加日期字段
QDateEdit *birthEdit = new QDateEdit;
birthEdit->setCalendarPopup(true);
formLayout->addRow("出生日期:", birthEdit);

// 添加单选按钮
QButtonGroup *genderGroup = new QButtonGroup;
QHBoxLayout *genderLayout = new QHBoxLayout;
QRadioButton *maleBtn = new QRadioButton("男");
QRadioButton *femaleBtn = new QRadioButton("女");
genderLayout->addWidget(maleBtn);
genderLayout->addWidget(femaleBtn);
genderGroup->addButton(maleBtn);
genderGroup->addButton(femaleBtn);
maleBtn->setChecked(true);
formLayout->addRow("性别:", genderLayout);

// 添加多行文本
formLayout->addRow("个人简介:", new QTextEdit);

// 设置标签对齐方式
formLayout->setLabelAlignment(Qt::AlignRight);

10. 自定义控件:释放创造力

10.1 继承现有控件

示例:增强版QSlider

class VolumeSlider : public QSlider {
    Q_OBJECT
public:
    VolumeSlider(QWidget *parent = nullptr) 
        : QSlider(Qt::Horizontal, parent) {
        setRange(0, 100);
        setValue(50);
    }

protected:
    void paintEvent(QPaintEvent *event) override {
        QSlider::paintEvent(event);
        
        // 自定义绘制
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        
        // 绘制音量图标
        QRect iconRect(5, (height()-20)/2, 20, 20);
        painter.drawPixmap(iconRect, QPixmap(":/icons/volume.png"));
        
        // 绘制当前值
        painter.setPen(Qt::white);
        painter.drawText(width()-30, height()/2+5, 
                         QString::number(value()));
    }
    
    void mousePressEvent(QMouseEvent *event) override {
        // 点击任意位置跳转到该位置
        int newValue = minimum() + 
                      ((maximum()-minimum()) * event->x()) / width();
        setValue(newValue);
        event->accept();
    }
};

10.2 自定义绘制控件

示例:圆形进度条

class CircleProgress : public QWidget {
    Q_OBJECT
public:
    CircleProgress(QWidget *parent = nullptr) 
        : QWidget(parent), value(0), maxValue(100) {}
    
    void setValue(int val) { 
        value = qBound(0, val, maxValue); 
        update();  // 触发重绘
    }
    
protected:
    void paintEvent(QPaintEvent *) override {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        
        int side = qMin(width(), height());
        QRectF rect((width()-side)/2, (height()-side)/2, side, side);
        
        // 绘制背景圆
        painter.setPen(Qt::NoPen);
        painter.setBrush(QColor("#3A3A3A"));
        painter.drawEllipse(rect);
        
        // 绘制进度圆弧
        QPen pen(QColor("#05B8CC"));
        pen.setWidth(10);
        painter.setPen(pen);
        
        int startAngle = 90 * 16;  // 12点钟方向
        int spanAngle = -value * 360 * 16 / maxValue;
        painter.drawArc(rect.adjusted(5,5,-5,-5), startAngle, spanAngle);
        
        // 绘制中心文本
        painter.setPen(Qt::white);
        QFont font = painter.font();
        font.setPointSize(20);
        painter.setFont(font);
        painter.drawText(rect, Qt::AlignCenter, 
                         QString::number(value) + "%");
    }
    
private:
    int value;
    int maxValue;
};

10.3 组合控件

示例:搜索框组件

SearchBox
-QLineEdit* searchInput
-QPushButton* searchButton
-QAction* clearAction
+setPlaceholderText(text)
+text() : QString
+clear()
+searchRequested(QString)
QWidget

代码实现

class SearchBox : public QWidget {
    Q_OBJECT
public:
    SearchBox(QWidget *parent = nullptr) : QWidget(parent) {
        QHBoxLayout *layout = new QHBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);
        
        searchInput = new QLineEdit;
        searchButton = new QPushButton(QIcon(":/icons/search.png"), "");
        
        layout->addWidget(searchInput);
        layout->addWidget(searchButton);
        
        // 添加清除按钮
        clearAction = searchInput->addAction(
            QIcon(":/icons/clear.png"), QLineEdit::TrailingPosition);
        clearAction->setVisible(false);
        
        // 连接信号
        connect(searchButton, &QPushButton::clicked, 
                [this](){ emit searchRequested(searchInput->text()); });
        connect(searchInput, &QLineEdit::returnPressed, 
                [this](){ emit searchRequested(searchInput->text()); });
        connect(clearAction, &QAction::triggered, 
                [this](){ searchInput->clear(); });
        connect(searchInput, &QLineEdit::textChanged, 
                [this](const QString &text){ 
                    clearAction->setVisible(!text.isEmpty()); 
                });
    }
    
    void setPlaceholderText(const QString &text) {
        searchInput->setPlaceholderText(text);
    }
    
    QString text() const { return searchInput->text(); }
    void clear() { searchInput->clear(); }
    
signals:
    void searchRequested(const QString &text);
    
private:
    QLineEdit *searchInput;
    QPushButton *searchButton;
    QAction *clearAction;
};

结语

通过本文的学习,你已经掌握了Qt中30+核心控件的使用技巧。从基础按钮到高级图形视图,从布局管理到自定义控件,这些知识足以构建出专业级的GUI应用。

下一步学习建议

  1. 实践出真知:尝试组合不同控件创建复杂界面
  2. 探索Qt Designer:可视化设计界面,提高开发效率
  3. 学习样式表:使用QSS打造个性化UI
  4. 研究信号槽机制:深入理解Qt的事件处理
  5. 关注Qt官方博客:获取最新控件和技术动态

在评论区分享你的Qt开发经验或遇到的挑战,点赞收藏本文,下次需要控件参考时随时回来查阅!Qt的世界充满无限可能,期待看到你创造的精彩应用!

感谢您的阅读!期待您的一键三连!欢迎指正!

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【Air】

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值