1

I want to change the background color of QTabWidget tab background color. I managed it sub classing QTabBar and QTabWidget in my code then promote the QTabWidget to this new class. It works in my Ubuntu 18.04 machine using Qt 6.2.2 and Qt Creator 6.0.1.

I used the method mentioned here: Qt TabWidget Each tab Title Background Color

My custom tabwidget derived from QTabWidget and QTabbar:

`

#ifndef OZELTABWIDGET_H
#define OZELTABWIDGET_H

#include <QStyleOptionTab>
#include <QStylePainter>
#include <QTabWidget>

class OzelTabBar : public QTabBar {
public:
  OzelTabBar(const QHash<QString, QColor> &colors, QWidget *parent = 0)
      : QTabBar(parent) {
    mColors = colors;
  }

protected:
  void paintEvent(QPaintEvent * /*event*/) {

    QStylePainter painter(this);
    QStyleOptionTab opt;    

    for (int i = 0; i < count(); i++) {
      initStyleOption(&opt, i);
      if (mColors.contains(opt.text)) {
        opt.palette.setColor(QPalette::Button, mColors[opt.text]);
      }

      painter.drawControl(QStyle::CE_TabBarTabShape, opt);
      painter.drawControl(QStyle::CE_TabBarTabLabel, opt);
    }    

  }

private:
  QHash<QString, QColor> mColors;
};

class OzelTabWidget : public QTabWidget {
public:
  OzelTabWidget(QWidget *parent = 0) : QTabWidget(parent) {
    QHash<QString, QColor> SideTab;

    SideTab["Main"]      = QColor("yellow");
    SideTab["Settings"]  = QColor("cornflowerblue");
    SideTab["Account"]   = QColor("blue");
    SideTab["Server"]    = QColor("gray");
    SideTab["Records"]   = QColor("magenta");
    SideTab["Preset"]    = QColor("cyan");
    SideTab["Test"]      = QColor("red");



    setTabBar(new OzelTabBar(SideTab));
  }
};

#endif // OZELTABWIDGET_H





`

I got this working in Ubuntu machine, the image of the colored tab widget is in the attachment.

When i switched to Windows 10 machine with the same Qt version, it simply didn't work.

Is there anyone to help me to figure it out in Windows 10?

Thank you

enter image description here

Gokhan
  • 56
  • 4

1 Answers1

1

The answer is to add

QApplication a(argc, argv); a.setStyle("fusion");

to main.cpp and you get the colored tabs in Windows as you have in Linux machine

Gokhan
  • 56
  • 4
  • Thanks, I searched high and low, tried numerous stylesheets settings. This is the solution. If anyone is using Python, add these 2 lines to your code: app = QtWidgets.QApplication(sys.argv) and app.setStyle('fusion') – lollalolla Jun 21 '23 at 09:14