Qt Widgets global stylesheet



  • Does Qt allow to set stylesheets application-wide? It's very tedious to set them to each control by hand. It would be perfect if Qt allows to work with stylesheets like with an ordinary CSS - to write global selectors, make strict targeting with "id" attribute and so on.


  • Qt Champions 2016

    Yes !
    And its also recommended to do so
    as setting on each widget becomes a mess.
    QApplication have method.
    http://doc.qt.io/qt-5/qapplication.html#styleSheet-prop

    and yes, it has selectors as ClassType, name etc



  • @mrjj
    Ok, I understood that.
    Then I want to put a huge string literal that contains global stylesheet to project resources and pass it to the method you pointed above. Does Qt allow to move "hardcoded" strings to resources?


  • Qt Champions 2016

    @Tikani
    Yes, you can easy load a text file/stylesheet from resources. just use the special ":/" syntax and it just works
    Note that you must use QFile to load it.



  • @Tikani said in Qt Widgets global stylesheet:

    @mrjj
    Ok, I understood that.
    Then I want to put a huge string literal that contains global stylesheet to project resources and pass it to the method you pointed above. Does Qt allow to move "hardcoded" strings to resources?

    I think that the best practise for qt stylesheet is to use a ressource file on the qt ressource file named stylesheet.qss for example,

    You stylesheet.qss will contain this for example:

    stylesheet.qss

    QWidget
    {
    background-color: red;
    }
    QPushButton
    {
    color: yellow;
    }
    and then on your application you have to do something like this:

    QFile File("stylesheet.qss");
    File.open(QFile::ReadOnly);
    QString StyleSheet = QLatin1String(File.readAll());
    
    qApp->setStyleSheet(StyleSheet);
    

    I hope this can help you !



  • @mrjj, @mostefa
    Big thanks to both of you, I got the point.
    Marking as solved.


  • Qt Champions 2016

    Hi
    And for fooling around and testing you can do also do

    auto teststyle = R"(
                   QWidget
                   {
                   background-color: red;
                   }
                   QPushButton
                   {
                   color: yellow;
                   }
                   )";
    
    int main(int argc, char* argv[]) {
      QApplication a(argc, argv);
      a.setStyleSheet(teststyle);
      MainWindow w;
      w.show();
      return a.exec();
    }
    (c++ 11 compiler)
    

Log in to reply
 

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