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));
相关推荐
MC皮蛋侠客5 小时前
Google Test 单元测试指南
c++·单元测试·google test
艾莉丝努力练剑6 小时前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
eggcode6 小时前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
basketball6168 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
Fre丸子_10 小时前
自定义文件夹选取功能
c++
思麟呀11 小时前
C++工业级日志项目(六)异步日志器
linux·c++·windows
PAK向日葵12 小时前
从零实现 Python 虚拟机(二):S.A.A.U.S.O 的总体架构设计
c++·python
无限进步_12 小时前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
咩咦13 小时前
C++学习笔记30:友元类、内部类和封装
c++·学习笔记·类和对象·封装·内部类·友元类·friend
黄小白的进阶之路13 小时前
C++提高编程---3.6 STL-常用容器-queue 容器【P213~P214】
c++