Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Best way to use string in QML loaded from JSON



  • I'm working with Qt5.9.2 under Linux. My application reads a JSON file that contains an array of strings and put them into a QStringList. I also have an enum to easily retrieve the desired one. Example:

    text.json

    {
    	"TEXTS": [
                "Hello World!",
                "blablabla"
    	]
    }
    

    myclass.cpp

    enum Texts
    {
        HelloWorld,
        BlaBlaBla
    };
    
    QStringList _texts;
    // load strings to _texts
    
    _texts[HelloWorld]; // access to a string
    

    Now I need to use those strings in QML pages instead of hardcoded ones:

    Text {
        color: "#f1f5f5"
        text: "Hello World!"
    }
    

    My first thought is to create a Q_INVOKABLE function to retrieve the string on the fly. Something like:

    Text {
        color: "#f1f5f5"
        text: loadString(MyNamespace.HelloWorld);
    }
    

    but it requires to expose an enum to QML and I'm not sure if it's the best way. Any other idea?


  • Moderators

    @Mark81 said in Best way to use string in QML loaded from JSON:

    but it requires to expose an enum to QML

    why does it require an enum? Only if you design it that way. You could also pass a string?


Log in to reply