PDA

View Full Version : How to convert QVariant to my custom object?



troorl_ua
14th July 2007, 18:49
Hi!
I have custom model with list of my custom objects - QList<TBook *> bookList;
Also I have delegate in this model. In delegate I have index.model()->data(index, Qt::DisplayRole) - this is QVariant. How can I convert this to TBook? Here is definition of my custom class:

class TBook
{
public:
TBook(QString, QString, uint, QString, qreal);
TBook(){};
~TBook();
void setData(QString, QString, uint, QString, qreal);
QString getTitle();
QString getAuthor();
uint getGenre();
QString getPath();
qreal getProgress();
static QStringList getAllGenres();
void setTitle(QString);

private:
QString title;
QString author;
uint genre;
QString path;
qreal progress;
};
Q_DECLARE_METATYPE(TBook);

Please, help me:confused:

marcel
14th July 2007, 19:01
You can't really do that, not in a safe way, due to limitations of C++ unions -> limitations of QVariant.

The most elegant way would be to create user roles for every relevant getter of TBook. For example, for TBook::getTitle you create the BookTitleRole, and so on.
You should use these roles when requesting data from the model.

Regards

jpn
15th July 2007, 11:49
TBook book = qvariant_cast<TBook>(variant);

troorl_ua
15th July 2007, 18:59
TBook book = qvariant_cast<TBook>(variant);
Yes! It's working! Greate thanks! :)