Qt - 自定义标题栏思路
有两种思路:
思路一、
在UI文件中自定义

思路二、
自定义一个title类
CustomTitleBar.h
#pragma once
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
class CustomTitleBar : public QWidget
{
public:
CustomTitleBar(int w, int h, QWidget* parent = nullptr);
~CustomTitleBar();
private:
int m_w;
int m_h;
QLabel* titleLabel;
QPushButton* minButton;
QPushButton* maxButton;
QPushButton* closeButton;
QLabel* iconLabel;
};
CustomTitleBar.cpp
#include "CustomTitleBar.h"
CustomTitleBar::CustomTitleBar(int w, int h, QWidget* parent) :m_w(w),m_h(h), QWidget(parent)
{
// 设置对象名用于样式表匹配
setObjectName("customTitleBar"); // 新增关键代码
setFixedWidth(m_w);
setFixedHeight(m_h); // 推荐高度
// 创建控件
titleLabel = new QLabel("My Application");
minButton = new QPushButton("min");
maxButton = new QPushButton("max");
closeButton = new QPushButton("close");
// 图标
iconLabel = new QLabel;
iconLabel->setPixmap(QPixmap(":/icons/app_icon.png").scaled(20, 20, Qt::KeepAspectRatio));
// 设置黑色背景样式
setStyleSheet(
"#customTitleBar {"
" background: rgba(57,57,57,1);" // 黑背景
"}"
"#customTitleBar QLabel {"
" color: #FFFFFF;" // 修正文字颜色为白色
" font-weight: bold;"
" padding-left: 8px;"
"}"
"#customTitleBar QPushButton {"
" color: #FFFFFF;" // 按钮文字白色
" border: none;"
" background: transparent;"
" min-width: 30px;"
"}"
"#customTitleBar QPushButton:hover {"
" background: rgba(255,255,255,0.1);"
"}"
);
// 布局
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(iconLabel); // 添加到布局
layout->addWidget(titleLabel);
layout->addStretch();
layout->addWidget(minButton);
layout->addWidget(maxButton);
layout->addWidget(closeButton);
layout->setContentsMargins(5, 2, 5, 2);
// 连接信号
connect(minButton, &QPushButton::clicked, parent, &QWidget::showMinimized);
connect(maxButton, &QPushButton::clicked, parent, &QWidget::showMaximized);
connect(closeButton, &QPushButton::clicked, parent, &QWidget::close);
}
CustomTitleBar::~CustomTitleBar()
{
}

浙公网安备 33010602011771号