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

How to create Q_PROPERTYies that can handle javascript's array operator?



  • I'm trying to figure out how to evaluate expressions using the QJSEngine. I'm interested in just evaluating Javascript - not QML - but I know they're related in Qt, so I thought I'd post this here.

    Anyhow, I know in Javascript the [] operator is used like a lookup into a hash map. So myObject[3] and myObject["horse"] will respectively return the named child object mapped to those keys.

    I'd like to do something similar with the Scene object I'm designing that I plan to expose to the Javascript engine:

    class Node : public QObject
    {
        Q_OBJECT
        QString m_name;
    
    public:    
        Node(QWidget *parent = nullptr);    
        const QString& name() { return m_name; }
    }
    
    class Scene : public QObject
    {
        Q_OBJECT
        HashMap<int, Node*> m_nodeIdMap;
    
    public:    
        Scene(QWidget *parent = nullptr);
        Node* node(int id) { return m_nodeIdMap[id]; }
        
    public slots:
        void setNode(int id, Node* node) { m_nodeIdMap[id] = node; }
    };
    

    If I create an instance of Scene and expose it to my Javascript engine with the name 'scene', what would I need to do to have it be able to respond to javascript code like:

    print scene.node[3].name;
    

  • Qt Champions 2017

    Did you check whether qqmllistproperty can help ?



  • I did, but it seems like it is specific to lists rather than maps. I'd like to be able to handle strings as map values too.

    edit:
    I just found QQmlPropertyMap. This may be what I'm looking for. However, there is no example of how to use it as a property. It also seems to be a full hash map in and of itself rather than a wrapper around the hash I'm currently using.


Log in to reply