Change font of QTabWidget

  • I read that QTabWidget uses OS specific styling and it may be tricky to change the look. I experimented a lot but still can't figure it out.
    I subclassed both QTabWidget and QTabBar and set the custom TabBar.

    void TabBar::tabBarPaintEvent(QPaintEvent* event)
    	QStylePainter painter(this);
    	QStyleOptionTab opt;
    	for (int i = 0; i != count(); i++)
    		initStyleOption(&opt, i);
    		painter.setFont(QFont("Roboto", 15));
    		painter.drawControl(QStyle::CE_TabBarTabShape, opt);
    		painter.drawControl(QStyle::CE_TabBarTabLabel, opt);

  • Hi @krzysieklfc and welcome to Qt Forum.

    The QTabBar uses a default style to paint itself.
    You can change the font family, font size, background color and several properties using a QProxyStyle to change how the QTabBar is painted.

    #include <QProxyStyle>
    #include <QPainter>
    class TabBarProxyStyle : public QProxyStyle {
        TabBarProxyStyle(QStyle *style = nullptr) : QProxyStyle(style) { }
        void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override
            if (element == CE_TabBarTab) {
                painter->save(); // save the painter to restore later
                painter->setFont(QFont("Roboto", 15)); // change the defaul font of painter
                QProxyStyle::drawControl(element, option, painter, widget); // paint the TabBarTab using the default drawControl
                painter->restore(); // restore to default painter
                QProxyStyle::drawControl(element, option, painter, widget); // use default drawControl to paint all other components without changes.

    So, you just need to change the default style to the custom ProxyStyle

    tabWidget->tabBar()->setStyle(new TabBarProxyStyle);

Log in to reply