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 fromQuestion
there so I need to derive it fromQObject
.When I fetch the Questions randomly in
QuestionGenerator
it does not work becauseQVector
does net the not supported copy constructor ofQObject
.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.
-
@sandro4912
several options described here
https://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html -
I went for exposing a QQmlListProperty<Question> to QML. It works fine.