QTabWidget的每个tab居中显示图标和文本

使用QTabWidget,给每个tab添加了图标之后,文字和图标之间有间距,没有完美居中显示。

遇到此问题,尝试了多种办法,均不理想,最终自定义QTabBar,重绘tab,完美解决。

复制代码
#include <QTabBar>
#include <QStylePainter>

class MyTabBar : public QTabBar {
public:
    MyTabBar(QWidget *parent = nullptr) : QTabBar(parent)
    {
    }

protected:
    void paintEvent(QPaintEvent *) override
    {
        QStylePainter painter(this);
        for (int index = 0; index < this->count(); ++index) {
            QStyleOptionTab opt;
            initStyleOption(&opt, index);
            
            // 计算图标和文字的长度(含间距)
            int iconTextWidth = opt.iconSize.width()
                              + opt.fontMetrics.horizontalAdvance(opt.text)
                              + 4; // 4 是图标和文字的间距

            int x = (opt.rect.width() - iconTextWidth) / 2 + opt.rect.width() * index;

            painter.save();
            
            // 指定各状态下的按钮状态
            if (opt.state & QStyle::State_Selected) { // 按下状态
                painter.setPen(QColor(255, 255, 255));
                painter.fillRect(rect, QColor(31, 68, 133));
            } else if (opt.state & QStyle::State_MouseOver) { // 鼠标停留状态
                painter.setPen(QColor(255, 255, 255));
                painter.fillRect(rect, QColor(33, 72, 141));
            } else if (!(opt.state & QStyle::State_Enabled)) { // 禁止状态
                painter.setPen(QColor(255, 255, 255, 153));
                painter.fillRect(rect, QColor(84, 123, 192));
            } else { // 正常状态(默认)
                painter.setPen(QColor(255, 255, 255));
                painter.fillRect(rect, QColor(41, 90, 176));
            }

            QRect iconRect(x, (opt.rect.height() - opt.iconSize.height()) / 2,
                           opt.iconSize.width(), opt.iconSize.height());
            painter.drawPixmap(iconRect, opt.icon.pixmap(opt.iconSize));

            QRect textRect(iconRect.right() + 4, 0,
                           opt.rect.width() * (index + 1) - iconRect.right() - 4,
                           opt.rect.height());
            painter.drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, opt.text);
            painter.restore();
        }
    }
};

调用:

复制代码
ui->tabWidget->setTabBar(new MyTabBar(this));
相关推荐
深耕AI12 分钟前
【MFC简介:从基础概念到实际应用】
c++·mfc
六点半88823 分钟前
【C++】C++11 篇二
开发语言·c++
DDDDDDDRDDR30 分钟前
C++容器:list
开发语言·c++·stl
一拳一个呆瓜33 分钟前
【MFC】对话框属性:Use System Font(使用系统字体)
c++·mfc
Elnaij35 分钟前
从C++开始的编程生活(7)——取地址运算符重载、类型转换、static成员和友元
开发语言·c++
郝学胜-神的一滴1 小时前
Effective Modern C++ 条款26:避免在通用引用上重载
开发语言·c++·程序人生
草莓熊Lotso1 小时前
【C++】递归与迭代:两种编程范式的对比与实践
c语言·开发语言·c++·经验分享·笔记·其他
逐雨~3 小时前
9.8C++作业
开发语言·c++
疾风铸境8 小时前
qt+halcon开发相机拍照软件步骤
数码相机·qt·halcon·拍照
抠脚学代码9 小时前
Ubuntu Qt x64平台搭建 arm64 编译套件
数据库·qt·ubuntu