QTabBar文字对齐方式修改
尝试使用QSS修改
QTabBar{
text-align:left center;
}
QTabBar::tab{
text-align:left center;
}
失败!
查看帮助文档,也没找到能够修改对齐方式的函数,索性去查源码,一路跟踪到
case CE_TabBarTab:
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
proxy()->drawControl(CE_TabBarTabShape, tab, p, widget);
proxy()->drawControl(CE_TabBarTabLabel, tab, p, widget);
}
break;
发现目标,进入proxy()->drawControl(CE_TabBarTabLabel, tab, p, widget);
继续跟踪,找到最终绘制 CE_TabBarTabLabel 的地方
int alignment = Qt::AlignCenter | Qt::TextShowMnemonic;
if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget))
alignment |= Qt::TextHideMnemonic;
发现这里设置了对齐方式,然后调用
proxy()->drawItemText(p, tr, alignment, tab->palette, tab->state & State_Enabled, tab->text, QPalette::WindowText);
进行绘制。
修改对齐方式的方法
继承QProxyStyle,重写drawItemText函数
class TabStyle : public QProxyStyle
{
public:
using QProxyStyle::QProxyStyle;
virtual void drawItemText(QPainter* painter, const QRect& rectangle, int alignment,
const QPalette& palette, bool enabled, const QString& text,
QPalette::ColorRole textRole ) const override
{
alignment = Qt::AlignHCenter | Qt::AlignLeft;
QProxyStyle::drawItemText(painter,
rectangle,
alignment,
palette,
enabled,
text,
textRole );
}
};
修改前
修改后