PDA

View Full Version : How to expose dynamically amount of data to QML



sandro4912
25th September 2020, 15:26
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.

d_stranz
25th September 2020, 19:54
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.