Search code examples
qtstylesheetqt-designer

Where should Qt style sheet code be placed?


I have another question regarding Qt. I'm working in Qt Designer and am learning that style sheets are good way for creating custom appearances. However, I have a question regarding where the code should live.

Within Qt Designer, you have the option to right click on widgets and change style sheet options. This essentially places the style sheet code within the UI form which will later be processed behind the scenes.

However, let's say I want to change the appear (background color) of certain a vertical layout within the UI form. It doesn't appear that I have the ability to right click it to change the style within designer. Instead, I am forced to place code elsewhere within the project and use the "setStyleSheet(...)" method.

My question: where exactly should I place this code? Referring to all of the help documents, they just seem to use the setStyleSheet method but don't mention where the code should live. Should it live in the constructor? Or is there another area (like a config file) that should contain this?

I have no intention to make the styling be event driven, so I'm looking just to set it up at the beginning of the application and be done with it.

I appreciate any help!


Solution

  • A stylesheet is just a string that needs to be passed to setStyleSheet. Where and how you store the string is your choice. There are several ways you can do it.

    Method 1: Best method.

    Create a file, say, widget.qss and store your stylesheet data in it. Use QFile to read its contents and set the stylesheet.

    /* QSS File (widget.qss) */
    QWidget {
        background: gray;
        color: darkblue;
    }
    
    /* you source file (mywidget.cpp) */
    ....
    QFile styleFile( ":/widget.qss" );
    styleFile.open( QFile::ReadOnly );
    mywidget->setStyleSheet( QString::fromLatin1( styleFile.readAll() ) );
    styleFile.close();
    ....
    
    /* QRC File (resources.qrc) */
    <!DOCTYPE RCC><RCC version="1.0">
        <qresource prefix='/'>
            ....
            <file>widget.qss</file>
        </qresource>
    </RCC>
    
    /* QMake Project File (project.pro) */
    ....
    RESOURCES += resources.qrc
    

    Method 2: The header file method

    You can store the stylesheet string in a header file and add it to the source file. This is not a good way or the elegant way to do it. Prefer Method 1

    /* Header File (mywidgetstyle.h) */
    
    #ifndef MYWIDGETSTYLE_H
    #define MYWIDGETSTYLE_H
    
    include <QString>
    
    static QString mywidget_style = QString(
        "QWidget {"                     \
        "    background: gray;"         \
        "    color: darkblue;"          \
        "}"
    );
    
    /* Source File (mywidget.cpp) */
    
    #include "mywidgetstyle.h"
    
    ....
    setStyleSheet( mywidget_style )l
    ....