0

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?

nurdglaw
  • 2,107
  • 19
  • 37
  • Are you looking for [`QVariant::value`](https://doc.qt.io/qt-5/qvariant.html#value)? If not then please edit your question to provide a [mcve] that demonstrates what you're trying to achieve. – G.M. Mar 11 '20 at 12:22
  • You should convert your `QVariant` back to `MyType` in order to call its functions. – vahancho Mar 11 '20 at 12:24
  • @G.M. I was indeed looking for QVariant::value. Thank you. I think I read through the member functions in alphabetical order and was cross-eyed by the time I got to that one. If you convert you comment to an answer, I will accept and upvote it. – nurdglaw Mar 11 '20 at 12:31

1 Answers1

1

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();
}
G.M.
  • 12,232
  • 2
  • 15
  • 18