Search code examples
cssqtstylesheetqt4.8qtabwidget

Styling QTabWidget


I have a QTabWidget with a background gradient and two problems.

  1. How dow I remove the anoying outline around the active tab (see image)? I tried "outline: none" like with push buttons but it does not seem to have an effect.

  2. How do I style disabled tabs? I tried :disabled and :!enabled but both do not work. // Edit: This works with :disabled but not with all properties. Seems like I tried the only not supported.

Anoying focus

The qt documentation was no help. Google either. :-(


Solution

  • It seems that the focus rectangle is handled by the QStyle (not to be confused with style sheets) that is in use. You can write a QStyle subclass and apply that to your to your QTabWidget. The subclass should override the drawControl() method and do nothing if it is currently drawing the focus rectangle.

    The subclass would look something like this:

    NoFocusRectStyle.h

    #ifndef NOFOCUSRECTSTYLE_H
    #define NOFOCUSRECTSTYLE_H
    
    #include <QWindowsVistaStyle> // or the QStyle subclass of your choice
    
    class NoFocusRectStyle : public QWindowsVistaStyle
    {
    public:
        NoFocusRectStyle();
    
    protected:
        void drawControl(ControlElement element, const QStyleOption *option, 
            QPainter *painter, const QWidget *widget = 0) const;
    };
    
    #endif // NOFOCUSRECTSTYLE_H
    

    NoFocusRectStyle.cpp

    #include "NoFocusStyle.h"
    
    NoFocusRectStyle::NoFocusRectStyle()
    {
    }
    
    void NoFocusRectStyle::drawControl(ControlElement element, 
        const QStyleOption *option, QPainter *painter, 
        const QWidget *widget) const
    {
        if(element == CE_FocusFrame)
            return;
    
        QWindowsVistaStyle::drawControl(element, option, painter, widget);
    }
    

    Somewhere in your form's intializer/constructor you would apply the custom style subclass to the tab widget:

    ui->tabWidget->setStyle(new NoFocusRectStyle());
    

    This should allow your style sheets to continue to work.

    It would be nice if there was an easier way to do this but I couldn't find one :)