[QGIS-Developer] PSA: Please don't use QVariant::canConvert in any new code

Nyall Dawson nyall.dawson at gmail.com
Thu Mar 17 15:36:32 PDT 2022


Hi list,

Quick heads up: please DON'T use QVariant::canConvert in any new code
introduced to QGIS. This function has had an extremely subtle change
of meaning in Qt6, so code which uses  canConvert will NOT work
correctly on Qt 6 builds.

To explain:

In Qt 5 this would return true if the value could be represented as
the specified type -- so calling .canConvert< QString >() would return
true for string and numeric variant values, but return false for some
object which can't be converted to a string (e.g. a QgsGeometry)

In qt 6 canConvert returns true if it's THEORETICALLY possible to
convert a variant to that type, regardless of what the value in the
variant actually is. So canConvert< QString >() returns true even if
the result of conversion would just be an empty string (e.g. when the
variant stores a geometry).

The only safe way to handle this situation now is by manually checking
the QVariant.type().

Nyall


More information about the QGIS-Developer mailing list