Question

I have a QTabWidget that contains 4 tabs. I would like to style each header of them individually : I saw I could use stylesheet to possibly do that. But my problem is that I couldn't just change the header of one tab, where the name of the tab is, without changing the rest of the tab.

In a simple way, imagine I want to have the first tab red, the second blue, 3rd green and the 4th yellow. So, how can I change the style of every single tab without changing the others.

Thanks!

EDIT

I saw there how I could change the style of all tab headers at once, but not individually

Was it helpful?

Solution

If you subclass QTabWidget, you can access the protected function QTabWidget::tabBar(), which returns the QTabBar it uses. QTabBar has a method QTabBar::setTabTextColor() that will change the text color of an individual tab. Here is an example:

#include <QtGui>

class TabWidget : public QTabWidget
{
public:
    TabWidget()
    {
        addTab(new QPushButton("Hi 1!"), "Button 1 Tab");
        addTab(new QPushButton("Hi 2!"), "Button 2 Tab");
        tabBar()->setTabTextColor(0, QColor(Qt::red));
        tabBar()->setTabTextColor(1, QColor(Qt::blue));
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    TabWidget tabWidget;

    tabWidget.show();
    return app.exec();
}

If you need more control, you can make your own tab widget. According to the docs, QTabWidget is basically just a QStackedWidget combined with a QTabBar. You can make your own tab widget by combining a QStackedWidget with, for example, a set of stylized QPushButtons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top