Qt-改变tabBar位置并改变文字方向

QTabWidget默认tab页标题(tabBar)在上面,但是有时候我们需要改变它的位置,比如做一个设置页面,想将它放到左边显示,这个比较简单,只需要设置一个属性即可实现:tabPosition:west,但是我们发现它文字的方向是没有改变的,这样完全没有使用体验,所以我们需要改变文字的方向。

为了改变文字的方向,我们需要自定义tabBar的样式,QProxyStyle这个类就可以帮助我们实现,QProxyStyle覆盖QStyle(默认的系统样式),用于动态覆盖绘图或其他特定的样式行为。如果想要实现自定义样式,需要自己定义一个类,派生QProxyStyle,实现对应的虚函数。

实现代码

1.创建界面及对应的头文件和源文件,在项目里头新建界面,比如setting,新建成功我们得到setting.h,setting.ui,setting.cpp这三个文件,然后界面添加标签页控件。

2.编写对应的代码

//setting.h
#ifndef SETTING_H
#define SETTING_H

#include <QWidget>
#include <QProxyStyle>
#include <QStyleOptionTab>
#include <QPainter>

namespace Ui {
class Setting;
}

class Setting : public QWidget
{
    Q_OBJECT

public:
    explicit Setting(QWidget *parent = nullptr);
    ~Setting();

private:
    Ui::Setting *ui;
};

//自定义tabbar的样式
class CustomTabStyle:public QProxyStyle{
public:
    CustomTabStyle(){}
    QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const;
    void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const;
};
#endif // SETTING_H
//setting.cpp
#include "setting.h"
#include "ui_setting.h"

Setting::Setting(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Setting)
{
    ui->setupUi(this);
    ui->tabWidget->tabBar()->setStyle(new CustomTabStyle);
}

Setting::~Setting()
{
    delete ui;
}

QSize CustomTabStyle::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.transposed();
        s.rwidth()=100;
        s.rheight()=50;
    }
    return s;
}
void CustomTabStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
    if(element==CE_TabBarTabLabel){
        if(const QStyleOptionTab *tab=qstyleoption_cast<const QStyleOptionTab *>(option)){
            QRect allRect=tab->rect;
            if(tab->state&QStyle::State_Selected){
                painter->save();
                painter->setPen(0x89cfff);
                painter->setBrush(QBrush(0x89cfff));
                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(0x000001);
            }
            painter->drawText(allRect,tab->text,option);
            return ;
        }
    }
    if(element==CE_TabBarTab){
        QProxyStyle::drawControl(element,option,painter,widget);
    }
}

3.效果预览

参考资料

QTabWidget 改变tabBar位置 并改变文字方向_skyztttt的专栏-CSDN博客

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注