c++qtqt5qtstylesheets

How can I apply a custom theme?


I am using QtCreator to create a Qt Application in C++.

I know CSS and making themes for elements in my applications isn't too hard, but is there a way to make a file and apply it?

I've looked through the Qt Docs but I can't seem to find anything about such a thing.

Currently, I am styling each individual button and stuff but can I just put it all in a file and apply it to everything at once?


Solution

  • Create a file, e.g., style.myStyle. There, you place the styles for all the widgets including events, attributes, etc. Then, load the file when the app starts, and apply that to the app:

    #include <QApplication>
    #include <QFile>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QFile file("./style.myStyle");
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        a.setStyleSheet(styleSheet);
        MainWindow w;
        w.show();
        return a.exec();
    }
    

    Now in the style.myStyle file, you can do customize your style, e.g:

    QPushButton
    {
        background-color: white;
        border-style: outset;
        border-width: 2px;
        border-radius: 10px;
        border-color: beige;
        font: bold 14px;
        min-width: 10em;
        min-height: 20em;
        padding: 6px;
    }
    QPushButton:pressed
    {
        background-color: rgb(224, 0, 0);
        border-style: inset;
    }
    QFrame, QLabel, QToolTip
    {
        border: 2px solid green;
        border-radius: 2px;
        padding: 1px;
    }
    

    That code produces this:

    enter image description here

    Note: Make sure to validate that the file exists, etc.