Is there a possibility to automatically convert QVariants to Python objects?

StackOverflow https://stackoverflow.com/questions/1372557

  •  21-09-2019
  •  | 
  •  

문제

PyQt 4.5.4, Python 2.6.2

Since version 4.5.2 PyQt is able to accept any Python objects where formerly only QVariants were allowed. This leads to some problems:

>>> itemModel.data(index, Qt.EditRole)
<Product object at 0xb7ce766c>
>>> index.data(Qt.EditRole)
<QVariant object at 0xb7ce768c>

Is there a possibility to remove this inconsistence?

도움이 되었습니까?

해결책

PyQt 4.6, using the modern API:

The QVariant class is implemented as a mapped type. Any Python object can be passed when a QVariant instance is expected. When Qt returns a QVariant then it will automatically be converted to the original Python object or an equivalent. None is interpreted as an invalid QVariant and vice versa.

다른 팁

You could use the .toPyObject() method on a QVariant. I doubt that this works for custom types, though.

The only solution I have found is converting every value to a QVariant and then back:

QVariant(possiblyAQVariant).toPyObject()

This works for QVariants and Python types.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top