How can I extract the underlying value from QVariant?
-
I have a Model class of my own and need to extract the underlying value of the QVariant. That is, if the value in QVariant is a double I need to convert from QVariant to double, for instance.
Do I need to do a switch with types? is QVariant::metaType the way to find the kind of value inside the QVariant? Can you show an example? -
@jdent For basic types there are obvious QVariant methods like QVariant::toDouble(). The QVariant documentation is quite useful.
You can also register and handle custom types through QVariant. In that case you would use:
Q_DECLARE_METATYPE(MyCustomType); MyCustomType foo; QVariant v = QVariant::fromValue(foo); MyCustomType bar = v.value<MyCustomType>();
or similar functions depending on Qt version.
-
@jdent said in How can I extract the underlying value from QVariant?:
Do I need to do a switch with types? is QVariant::metaType the way to find the kind of value inside the QVariant? Can you show an example?
This would be one way to go. I have never had a need for this, but I'll give it a try how you could solve this with a switch statement:
switch(myVariant.metaType().id()) { case QMetaType::fromType<int>().id(): // handle int break; case QMetaType::fromType<QString>().id(): // handle QString break; default: // maybe a message/log that this case is unhandled break; }
(I have never used QMetaType this extensively. I hope that calling
id()
is the smartest choice to distinguish these cases.)std::variant also has a solution with the overload pattern (using lambdas) using std::visit. It might be possible to use the overload pattern with std::visit on QVariants as well.