8

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)

zerocukor287
  • 555
  • 2
  • 8
  • 23
alphanumeric
  • 17,967
  • 64
  • 244
  • 392

1 Answers1

15

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
László Papp
  • 51,870
  • 39
  • 111
  • 135