From adb8db43722306bd11e8c3da3d026a50374266e9 Mon Sep 17 00:00:00 2001 From: Tsu Jan Date: Thu, 25 Apr 2024 22:19:12 +0330 Subject: [PATCH] Fixed inactive tab text with Qt6 Due to a change (or bug?) in Qt6, using a stylesheet for setting the font of active/inactive tabs doesn't work as it did with Qt5. Here, `QStyle` is used directly, which is always the best approach because stylesheets can interfere with the widget style in bad ways. Fixes https://github.com/lxqt/qterminal/issues/1112 --- src/tabbar.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/src/tabbar.cpp b/src/tabbar.cpp index 16c1e0d5..fbe5c0cd 100644 --- a/src/tabbar.cpp +++ b/src/tabbar.cpp @@ -17,19 +17,59 @@ ***************************************************************************/ #include "tabbar.h" +#include +#include +#include + +class TabTextStyle : public QProxyStyle +{ // Give a normal font to inactive tabs. +public: + using QProxyStyle::QProxyStyle; + void drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const override + { + bool painterSaved = false; + if (element == QStyle::CE_TabBarTabLabel) + { + if (const auto opt = qstyleoption_cast(option)) + { + if (const auto tb = qobject_cast(widget)) + { + int indx = tb->currentIndex(); + if (indx > -1 && !tb->tabRect(indx).contains(opt->rect.center())) + { + QFont f = painter->font(); + f.setBold(false); + painter->save(); + painterSaved = true; + painter->setFont(f); + } + } + } + } + QProxyStyle::drawControl(element, option, painter, widget); + if (painterSaved) + { + painter->restore(); + } + } +}; TabBar::TabBar(QWidget *parent) : QTabBar(parent), mFixedWidth(false), mFixedWidthValue(0) { - // To make the selected tab text bold, first give a bold font to the tabbar - // for QStyle::sizeFromContents(QStyle::CT_TabBarTab, ...) to make room - // for the bold text, and then, set the non-selected tab text to normal. + // To make the text of the active tab bold, first give a bold font to the tabbar + // for QStyle::sizeFromContents(QStyle::CT_TabBarTab, ...) to make room for the + // bold text, and then use TabTextStyle as the style. + // WARNING: Using a stylesheet could result in elided texts with Qt6, + // although it worked with Qt5. QFont f = font(); f.setBold(true); setFont(f); - setStyleSheet(QStringLiteral("QTabBar::tab:!selected { font-weight: normal; }")); + TabTextStyle *s = new TabTextStyle; + s->setParent(this); + setStyle(s); } void TabBar::setFixedWidth(bool fixedWidth)