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));
相关推荐
不想写代码的星星5 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
Felix_One1 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
哇哈哈20219 天前
信号量和信号
linux·c++
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc