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

StackOverflow https://stackoverflow.com/questions/15916135

  •  03-04-2022
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

I set the stylesheet when the application is run from an external file. Also, for the designer we added a button to 'reload stylesheet'. This way the designer can modify the file and try the changes immediately.

For example:

QFile styleFile("stylesheet.qss");
styleFile.open(QFile::ReadOnly);
QByteArray bytes = styleFile.readAll();
QApplication *app = (QApplication*)QApplication::instance();
app->setStyleSheet(newStyleSheet);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top