Can't get my object back from QVariant

  • This is how encode my object (ContactPtr) as QVariant

    @QVariant ContactsModel::data(const QModelIndex &index, int role) const
    if (!index.isValid())
    return QVariant();

    if (index.row() >= this->contacts.size())

    return QVariant();

    if (role == Qt::DisplayRole)

    ContactPtr ptr = const_cast<Contact*>(&this->contacts[index.row()]);
    return QVariant(QVariant::UserType, &ptr);
    return QVariant();

    At some point in the rendering delegate, I am trying to get the ContactPtr back from the QVariant. I cannot get past the compilation errors for this. Everything I try fail. The ContactPtr is registered with:

    @typedef Contact * ContactPtr;

    Can someone please help to point me in the right direction? I'd like to:

    // qv is my QVariant.
    @ContactPtr ptr = qv.value<ContactPtr>;@

    but it fails compilation. How do I do this??

  • youz are using the wrong functions, if you look at "the docs": . Use "qVariantFromValue": instead.

    The point is with Q_DECLARE_METATYPE, you define an id for your type, which migth be QVariant::UserType, but also something else.

    To get it back, use "qVariantValue":

  • What type is ContactPtr? Just a

    typedef Contact* ContactPtr

    or something else?

    In the return line you put a pointer to the ptr (which is of type ContactPtr) object, i.e. you put a ContactPtr* into the QVariant. ptr obviously goes out of scope, once you leave the data() method, so you have a dangling pointer in your QVariant.

  • Ok. I've cancelled the ContactPtr. There was no real need for it. Now I do:


    I encode into QVariant like this:

    @return qVariantFromValue(const_cast<Contact*>(&this->contacts[index.row()]));@

    But I still cannot decode:

    void ContactDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
    Contact * contact = qVariantValue(; // <---- error:

    ContactDelegate.cpp:15: error: no matching function for call to 'qVariantValue(QVariant)'

  • qVariantValue is a template function. You must call:

    Contact * contact = qVariantValue<Contact *>(;

  • That did the job. I missed that little detail as the documentation's title is: "T qVariantValue ( const QVariant & value )"

    Thanks Volker and Gerolf

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.