QMap access in QML



  • I have 10 properties, each defined in a c++ class as follows:

    Q_PROPERTY(float titleWidget1 READ titleWidget1 NOTIFY titleWidgetChanged1)
    float titleWidget1() const{return m_titleWidget1;}
    

    The class is exposed to my QML, which currently works nicely, such that I can update QML text with myClass.titleWidget1. This approach doesn't scale particularly well, as I'm having to do a lot of if (selectedWidget == 1) statements to set the QML text to the correct widget number.

    As such, I'd like to replace the above implementation with a QMap, so I can have the following functionality:

    map<int, string> widgetTitle;
        for (int i(1); i < 11; i++) {    
    	widgetTitle[i] = "widgetTitle" + i;
    

    Then in QML, I'd be able to assign text as follows:

    text: myClass.widgetTitle[selectedWidget]
    

    Where selectedWidget is an exposed property I use to store the map index to be used in QML.

    Is the above a logical approach? QML will need to be able to update on changes to the map, so I don't believe a QStringList, QVariantList or QObjectList are suitable. Could the above functionality be provided with a QAbstractItemModel, or is there a way I can use a QMap?



  • To make it a little clearer, imagine I've got multiple QProperties for each of the 10 hypothetical widgets:

    widgetSizeX1
    widgetSizeY1
    widgetColour1
    widgetTitle1
    //etc
    

    If each of the above were contained in a QMap, so that I could read/set the values for each of the 10 widgets as follows:

    map<int, int> widgetSizeX
        for (int i(1); i < 11; i++) {
           widgetSizeX[i] = i
           //This would make Widget1 1px wide and Widget10 10px wide (for example).
        }
    

    Then in QML, if Widget 4 was selected, such that selectedWidget == 4, I could use the map values from c++ to set properties of the relevant QML item:

    width: myClass.widgetSizeX[selectedWidget]
    height: myClass.widgetSizeY[selectedWidget]
    //etc.
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.