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:
{
Q_OBJECT
Q_PROPERTY(int id READ id)
Q_PROPERTY(QString askedQuestion READ askedQuestion
) public:
Question(int id,
int getId() const;
private:
int mId;
};
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;
};
To copy to clipboard, switch view to plain text mode
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;
}
};
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;
}
};
To copy to clipboard, switch view to plain text mode
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.
Bookmarks