Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a Qt stylesheet to an external file but keep it compiled in resources?

My Qt application has a large stylesheet with lots of margins, pixels and other stuff directly based on and related to drawing and graphics. I would be happy to give all that stuff to the designer, but the stylesheet is kept within the .ui file which is not convenient for the designer; she'd prefer to see a separate file and edit it using her usual tools.

What I want is moving the stylesheet to an external .qss file, adding that file to the program resources and linking it to the .ui file, so the stylesheet would be compiled and used by the widget automatically, and the application wouldn't have to keep the stylesheet file and load it at runtime.

How to achieve that?

like image 771
Alexander Dunaev Avatar asked Apr 10 '13 02:04

Alexander Dunaev


People also ask

How do I add a styleSheet to Qt?

You can right-click on any widget in Designer and select Change styleSheet... to set the style sheet. In Qt 4.2 and later, Qt Designer also includes a style sheet syntax highlighter and validator.

What is a QRC document?

qrc file, an XML-based file format that lists files on the disk and optionally assigns them a resource name that the application must use to access the resource.


1 Answers

Copy all your styles into a file and rename it to something like stylesheet.qss Then include it in your qrc file as a new resource item. You can simply do this by editing your qrc file, if you already have one. Refer documentation on how to add a new resource.

Then modify your code like this to read the content of the qss file at run time and apply styles to your application.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QFile file(":/stylesheet.qss");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        a.setStyleSheet(file.readAll());
        file.close();
    }

    MainWindow w;
    w.show();

    return a.exec();
}

Note: when you do a change in the stylesheet.qss, you have to compile the qrc file for changes to take effect.

like image 90
warunanc Avatar answered Nov 15 '22 16:11

warunanc