Qt Custom Widgets, CSS and Layouts



  • I'm trying to figure out what logic Qt applies when it comes to loading in a CSS file and using the QApplication::setStyleSheet function. I have an application whereby my QMainWindow contains a number of QHBoxLayout and QVBoxLayout all containing promoted custom widgets derived from QWidget.

    I load in a CSS file into a QString before passing it into setStyleSheet. As I would expect, a lot of the styles of widgets change (push buttons, labels, etc) however, the custom widgets that I have inside the layouts behave rather oddly when it comes to being styles.

    As an example, my CSS file may contain the following styles:

    QPushButton {
        background-color: red;
    }
    
    MyWidget {
        background-color: blue;
    }
    
    

    If MyWidget widget is placed inside one of the QVBoxLayout or QHBoxLayout layouts then it would appear that the background colour is ignored. The QPushButton's are styled correctly as per the CSS. If I then add a CSS style overriding the QMainWindow background colour only then do I see a change to MyWidget - albeit the wrong change, the colour is taken from the QMainWindow widget.

    I'm already guessing that this isn't a very good explanation of my problem so in which case, I'll try and upload an example and link a screenshot here. To anyone that does understand, can anyone suggest anything? I can't quite figure out why Qt wouldn't apply my style when I explicitly give the name of the Widget class as the CSS class name.


  • Qt Champions 2016

    @webzoid
    Hi
    Did you custom widget override the paintEvent ?

    If yes, make sure you do in fact use the stylesheet

    void CustomWidget::paintEvent(QPaintEvent *)
     {
         QStyleOption opt;
         opt.init(this);
         QPainter p(this);
         style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
     }
    


  • @mrjj This has solved the problem. I've created by own base Widget which overrides the paintEvent as you've suggested and everything works beautifully. Thank you.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.