Skip to content

Commit

Permalink
Fixed inactive tab text with Qt6
Browse files Browse the repository at this point in the history
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 #1112
  • Loading branch information
tsujan authored and yan12125 committed Apr 29, 2024
1 parent 8c5ff85 commit adb8db4
Showing 1 changed file with 44 additions and 4 deletions.
48 changes: 44 additions & 4 deletions src/tabbar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,59 @@
***************************************************************************/

#include "tabbar.h"
#include <QPainter>
#include <QStyleOption>
#include <QProxyStyle>

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<const QStyleOptionTab*>(option))
{
if (const auto tb = qobject_cast<const QTabBar*>(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)
Expand Down

0 comments on commit adb8db4

Please sign in to comment.