QMetaType :: Float not in QVariant :: Type
I have an application that is working fine, but it was not compiled with warnings enabled. I'm trying to get it back and sort it but out of ideas on how to fix it. I have:
QVariant someVar
QVariant::Type variantType = someVar.type();
switch (variantType) {
case QMetaType::QString:
doSomething1();
break;
case QMetaType::Float:
doSomething2();
break;
}
and got this warning / error:
error: case value β135β not in enumerated type βQVariant::Typeβ [-Werror=switch]
in the line QMetaType :: Float. I checked the QT docs and listed QMetaType :: Float as value 38. What might be causing this?
The closest thing I can find is at https://github.com/qbittorrent/qBittorrent/issues/2510 which has the same error. Has anyone encountered this before?
source to share
Qt played some dirty tricks with the two enumerations ( QMetaType::Type
and QVariant::Type
). Citing 4.8.4 docs on QVariant::type()
:
Returns the storage type of the value stored in the variant. Although declared as a return function
QVariant::Type
, the return value must be interpreted asQMetaType::Type
. In particular,QVariant::UserType
it is only returned here if the value is equal or greaterQMetaType::User
.Note that the returned values ββin the
QVariant::Char
thruQVariant::RegExp
andQVariant::Font
thruQVariant::Transform
ranges correspond to theQMetaType::QChar
thruQMetaType::QRegExp
andQMetaType::QFont
thru rangesQMetaType::QQuaternion
.Also note that the types
void*
,long
,short
,unsigned long
,unsigned short
,unsigned char
,float
,QObject*
andQWidget*
are given inQMetaType::Type
but not inQVariant::Type
, and they can be returned by this function. However, they are considered user-defined types when tested againstQVariant::Type
.
In other words, the function QVariant::type()
returns the values QMetaType::Type
entered as QVariant::Type
, and the two enums share many (but not all) of their counters. This makes working with them in a strict type system tricky - they're basically wibbly-wobbly typey-wypey stuff.
In your case, note that the enumerator QMetaType::Float
is one that does not have a direct equivalent in QVariant::Type
.
I would say that the best way to silence the warning would be to change variantType
to QMetaType::Type
, perhaps on initialization on include and / or Qt-specific comments, if necessary.
source to share
Just turn it on QMetaType::Type
. This is indeed the case because the value QVariant::type()
matches the value QMetaType::Type
, even though the return type matters QVariant::Type
. This is the quirk / bug API you have to work with:
QVariant variant = ...;
switch (static_cast<QMetaType::Type>(variant.type())) {
...
}
source to share