Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From QVariant to Integer and String

The user's entered value can be both: a string or an integer.

QAbstractTableModel's setData() method always gets this value as QtCore.QVariant

Question:

How to implement if/elif/else inside of setData() to distinguish if the received QVariant is a string or an integer? (so a proper QVariant conversion method (such as .toString() or toInt()) is used)

P.s. Interesting that an attempt to convert QVariant toInt() results to a tuple such as: (0, False) or (123, True)

like image 967
alphanumeric Avatar asked Dec 25 '14 00:12

alphanumeric


1 Answers

You can check against the type:

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

Given that the form above is now obsolete, it is recommended to check it this way:

if myVariant.canConvert(QMetaType.Int):
    value = myVariant.toInt()
elif myVariant.canConvert(QMetaType.QString)
    value = myVariant.toString()
like image 59
lpapp Avatar answered Sep 22 '22 20:09

lpapp