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

How to expose dynamically amount of data to QML.



  • I have an app were I need to fetch random questions from a database and expose them to qml dynamically.

    So I created a class to store each dataset:

    class Question : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(int id READ id)
        Q_PROPERTY(QString askedQuestion READ askedQuestion)
    public:
        Question(int id,
                 QString askedQuestion);
    
        int getId() const;
        QString getAskedQuestion() const;
    
    private:
        int mId;
        QString mAskedQuestion;
    };
    

    And fill them in annother class. In reality it is derrived from an SQLDatabaseModel:

    class QuestionGenerator : public QObject
    {
        Q_OBJECT
    public:
        explicit QuestionGenerator(QObject *parent = nullptr);
    
        Q_INVOKABLE QVector<Question> getRandomQuestions(int count) const
        {
            // simplified in reality we fetch random questions from a database. 
            // the point is we need to add Questions to the vector
            // but this does not work since QObject based items cannot get copied
            QVector<Question> questions;
            questions.reserve(count);
            
            // add questions to vector
            
            return questions;
        }
    };
    

    I want to expose Question to QML to use the data from Question there so I need to derive it from QObject.

    When I fetch the Questions randomly in QuestionGenerator it does not work because QVector does net the not supported copy constructor of QObject.

    So how can I fix this?

    Again what I want:

    Fetch n Questions in C++ and expose them to QML so I can use the data to display.





  • I went for exposing a QQmlListProperty<Question> to QML. It works fine.


Log in to reply