Qt QTabWidget修改tabBar方向

感谢 https://blog.csdn.net/skyztttt/article/details/52448992

QTabWidget默认的 Tab方向是水平的,从属性设置更改 tabPosition=west后的效果如下图

Qt QTabWidget修改tabBar方向_第1张图片


最终效果图

Qt QTabWidget修改tabBar方向_第2张图片



#ifndef MH1_H
#define MH1_H

#include 
#include 
#include 
#include 

class CustomTabStyle : public QProxyStyle
{
public:
    /* sizeFromContents
     *  用于设置Tab标签大小
     * 1.获取原标签大小
     * 2.宽高切换
     * 3.强制宽高
     * 4.return
     * */
    QSize sizeFromContents(ContentsType type, const QStyleOption *option,
        const QSize &size, const QWidget *widget) const
    {
        QSize s = QProxyStyle::sizeFromContents(type, option, size, widget);
        if (type == QStyle::CT_TabBarTab) {
            s.transpose();
            s.rwidth() = 120; // 设置每个tabBar中item的大小
            s.rheight() = 44;
        }
        return s;
    }

    /* drawControl
     *  画控件
     * 1.过滤CE_TabBarTabLabel
     * 2.选择状态下的背景绘制
     *      a.获取Rect
     *      b.保存旧的画笔
     *      c.设置新画笔
     *      d.画 Rect
     *      e.恢复旧的画笔
     * 3.设定Text对齐及选中/非选中状态下的Text颜色
     * 4.过滤CE_TabBarTab,对其进行绘制
     * */
    void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
    {
        if (element == CE_TabBarTabLabel) {
            if (const QStyleOptionTab *tab = qstyleoption_cast(option))
            {
                QRect allRect = tab->rect;

                if (tab->state & QStyle::State_Selected) {
                    painter->save();
                    painter->setPen(0x89cfff);
                    painter->setBrush(QBrush(0x89cfff));
                    QRect nrct = allRect.adjusted(6, 6, -6, -6);
                    painter->drawRect(allRect.adjusted(6, 6, -6, -6));
                    painter->restore();
                }
                QTextOption option;
                option.setAlignment(Qt::AlignCenter);
                if (tab->state & QStyle::State_Selected) {
                    painter->setPen(0xf8fcff);
                }
                else {
                    painter->setPen(0x5d5d5d);
                }

                painter->drawText(allRect, tab->text, option);
                return;
            }
        }

        if (element == CE_TabBarTab) {
            QProxyStyle::drawControl(element, option, painter, widget);
        }
    }
};


#endif // MH1_H

你可能感兴趣的:(qt,CPP)