Important: Please read the Qt Code of Conduct -

[SOLVED] Stylesheet from file - relative url paths

  • Ok, so in my application i apply a stylesheet from a file, like this:
    in main:
    @QFile file(QApplication::applicationDirPath() + "/themes/default/style.css");;
    QString StyleSheet = QLatin1String(file.readAll());

    and in the style.css, i want to use an image like this
    @image: url(down-arrow.png);@

    but the thing is that qt searches for the file "down-arrow.png" inside the folder of the exe (QApplication::applicationDirPath() )

    so i have to write
    @image: url(themes/default/down-arrow.png);@

    is there any way to use relative paths in the stylesheet file?

    or in other words, to change where qt searches for files when it parses the stylesheet

    Thank you

  • You can in style.css write:
    image: url(%down-arrow.png%);
    then load stylesheet to QString and replace %down-arrow.png% to correct file. I don't know other solution.

  • well that wouldnt help i think, cuz i give the user the abillity to set their own theme folder and so they can make their own style.css file.. (though i didnt understand how to change the %down-arrow.png% ... something with args?)

    but i figured a way when you said about QString replacement, so thank you! :)

    @QString styleSheetFromFile(QString file, QString folderForUrl)
    QFile f(file);;
    QString styleSheet = QLatin1String(f.readAll());
    return styleSheet;

  • You load the style sheet by yourself. With this, Qt has no idea where your style sheet comes from. This also means, that a relative path to the images makes no sense. Qt just looks relative to the current working directory; in your case relative to the executable.
    The solution is as simple as undocumented:
    QApplication a(argc, argv);
    QString file = "/path/to/fancy.css";
    a.setStyleSheet( "file:///" + file);

Log in to reply