nurdglaw
nurdglaw

Reputation: 2127

Recover user-defined type stored in QVariant

I've seen How to verify QVariant of type QVariant::UserType is expected type? and I understand how to tell that an object of class MyType has been stored in a QVariant object. I've read the documentation for QVariant::convert () but I don't follow how I call a member function defined in MyType for an object that I have received as a QVariant.

Say I have

class MyType
{
public:
    void myFunction;
    .
    .
    .
};
Q_DELCARE_METATYPE(MyType)
MyType m;
QVariant var (QVariant::fromValue (m));

How do I call MyType::myFunction for the MyType object saved at var?

Upvotes: 0

Views: 399

Answers (1)

G.M.
G.M.

Reputation: 12879

As per the comment, you can use QVariant::value to obtain a copy of the object held by the QVariant. So in this particular case something like...

/*
 * Check that the conversion is possible.
 */
if (var.canConvert<MyType>()) {

  /*
   * Obtain a copy of the MyType held.
   */
  auto m = var.value<MyType>();

  /*
   * Use as per normal.
   */
  m.myFunction();
}

Upvotes: 1

Related Questions