QML: how to specify image file path relative to application folder

前端 未结 3 996
天命终不由人
天命终不由人 2020-12-10 03:00

We are developing our first Qt/QML application (trying technology). While technology looks very promising at a glance, we have faced so many unexpected weird issues that alm

相关标签:
3条回答
  • 2020-12-10 03:31

    If you can't use a .qrc file for your images, you could try this:

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
        return app.exec();
    }
    

    In QML, you'd then do:

    Image {
        source: "file:///" + applicationDirPath + "/../resources/images/image.png"
    }
    

    Note that this code is not tested.

    0 讨论(0)
  • 2020-12-10 03:33

    Old questions, but got here from google. For me, it works simply with a relative path like this:

    import QtQuick 2.12
    import QtQuick.Controls 2.12
    import QtQuick.Layouts 1.3
    
    [...]    
    
    Image {
        id: image
        source: "icons/brightness.svg" // simple relative path
        width: 22
        height: 22
        sourceSize.width: 22 // svg render resolution
        sourceSize.height: 22
        fillMode: Image.PreserveAspectFit // just in case to avoid stretching
    }
    

    no .qrc needed.

    0 讨论(0)
  • 2020-12-10 03:35
    Image {
       source: "file:resources/images/image.png"
    }
    

    will work if the working directory is set to the ApplicationFolder

    note: when running from QtCreator, double check what directory the application is actually running in (i had my application run in my home directory even though the working directory was set correctly in the run configuration (after running it once in a terminal window this magically fixed itself) )

    0 讨论(0)
提交回复
热议问题