To know if a QVariant
is a QString
or an integer you have to use QVariant::type()
or QVariant::userType()
.
bool isInteger(const QVariant &variant)
{
switch (variant.userType())
{
case QMetaType::Int:
case QMetaType::UInt:
case QMetaType::LongLong:
case QMetaType::ULongLong:
return true;
}
return false;
}
bool isString(const QVariant &variant)
{
return variant.userType() == QMetaType::QString;
}
If you use other methods to get the type of the variant, you will get wrong answers.
For instance:
// This function does not work!
bool isInteger(const QVariant &variant)
{
bool ok = false;
variant.toInt(&ok);
return ok;
}
QString aString = "42";
QVariant var = aString;
isInteger(var); // Returns true, but var.type() returns QMetaType::QString !!!
Now if you want to know if a QVariant
can be converted to an integer, you have the beginning of an answer in Qt Documentation:
Returns the variant as an int if the variant has userType()
QMetaType::Int, QMetaType::Bool, QMetaType::QByteArray,
QMetaType::QChar, QMetaType::Double, QMetaType::LongLong,
QMetaType::QString, QMetaType::UInt, or QMetaType::ULongLong;
otherwise returns 0.
Which means that there are many non integer variants that can be converted to an integer. The safest way to do it is to use QVariant::canConvert()
and QVariant::value()
:
QString aString = "42";
QVariant var = aString;
if (var.canConvert<int>())
{
auto anInteger = var.value<int>();
}