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:
Code:
{
Q_OBJECT
Q_PROPERTY(int id READ id)
Q_PROPERTY(QString askedQuestion READ askedQuestion
) public:
Question(int id,
int getId() const;
private:
int mId;
};
And fill them in annother class. In reality it is derrived from an SQLDatabaseModel:
Code:
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.
Re: How to expose dynamically amount of data to QML
Quote:
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?
Store Question * instead of Question in your QVector. Use qDeleteAll() followed by QVector::clear() to delete the contents of the QVector without a memory leak.