From QVariant to Integer and String

The user entered valuecan be either a string or an integer.

QAbstractTableModel setData()the method always gets this valueasQtCore.QVariant

Question

How to implement if/elif/elseinternally setData()to distinguish whether the resulting QVariantstring or integer? (therefore, the correct conversion method is used QVariant(such as .toString () or toInt ())

Ps Interestingly, trying to convert QVarianttoInt () results in a tuple, for example: (0, False)or(123, True)

+4
source share
1 answer

You can check the type :

if myVariant.type == QVariant.Int:
    value = myVariant.toInt()
elif myVariant.type == QVariant.QString:
    value = myVariant.toString()

, , :

if myVariant.canConvert(QMetaType.Int):
    value = myVariant.toInt()
elif myVariant.cannConvert(QMetaType.QString)
    value = myVariant.toString()
+6

Source: https://habr.com/ru/post/1568937/