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));
相关推荐
卷无止境20 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境20 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴2 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境4 天前
C++ 的Eigen 库全解析
c++
卷无止境4 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴4 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
Quz5 天前
QML Hello World 入门示例
qt
博客18006 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴6 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨7 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++