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

Q_PROPERTY for single item in map?



  • I am working on binding some values between QML/c++. I am wondering if something like this is possible?
    Basically I have the single "property" stored in a map and a function that returns the entity pointer from the map given a specific key.

    Can I use Q_PROPERTY macro to hard code distinct pieces. Bascially the board has 100 slots for 100 pieces. I could hard code 100 distinct Pieces and not use a map or list, or I could use a Map and just present these arbitrary properties to the QML side of things so I can say things like

    value: board.piece1.status
    

    Here is some code to illustrate my point in C++

    #ifndef BOARD_H
    #define BOARD_H
    
    #include "dataclassbase.h"
    #include "piece.h"
    
    class Board : public DataClassBase
    {
        Q_OBJECT
        Q_PROPERTY(Piece* piece1 READ getPieceStatus(1) NOTIFY pieceStatusChange)
        Q_PROPERTY(Piece* piece2 READ getPieceStatus(2) NOTIFY pieceStatusChange)
        Q_PROPERTY(Piece* piece3 READ getPieceStatus(3) NOTIFY pieceStatusChange)
        Q_PROPERTY(Piece* piece4 READ getPieceStatus(4) NOTIFY pieceStatusChange)
    //  .
    //  .
    //  .
        Q_PROPERTY(Piece* piece100 READ getPieceStatus(100) NOTIFY pieceStatusChange)
    
    public:
        Board(QObject *parent = nullptr);
    
        Piece* getPieceStatus(int key);
    
    private:
    
        /* maps hold the data to the results for each piece */
        QMap<int,Piece*> pieceStatusMap;
    
    };
    
    #endif // BOARD_H
    

    Let me know,
    thank you
    Shawn


  • Lifetime Qt Champion

    Hi,

    Sounds you look for something like QQmlListProperty.



  • Actually, yes, yes it does sir. I will look into this tyvm!



  • Spent some time with QQmlPropertyList - couldn't quite get it to work. In QML code when I access it I get a QVariant(QQmlPropertyList) and I have now idea how to access elements in it.


  • Lifetime Qt Champion

    Might be a silly question but did you took a look at example linked in the class documentation ?



  • Yea, I spent a good chunk of time staring at the example and try to get it working in my context but it didn't quite work out. I eventually just made an invokable getter method that takes the index and using signals from the c++ class I tell the QML file when to update it's respective values with the getter method into my list.


Log in to reply