PyQt4.QtCore.QVariant object instead of a string?

前端 未结 1 394
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 08:27

I followed this example Key/Value pyqt QComboBox, to store ID value to a combo-box item using the code below.

self.combox_widget.addItem(\'Apples\', \'Green\         


        
相关标签:
1条回答
  • 2021-01-14 08:48

    Most Qt APIs that set and retrieve arbitrary "data" will store it as a QVariant.

    For Python2, by default, PyQt will automatically convert a python object to a QVariant when you set it, but it won't automatically convert them back again when you retrieve it. So you have to take an extra step to do that like this:

        print self.combox_widget.itemData(indx).toPyObject()
    

    For Python3, by default, the conversion is always done automatically in both directions, so the extra step is not needed.

    To workaround this difference, PyQt provides a way to explicitly set the default mode by using the sip module:

    import sip
    sip.setapi('QVariant', 2)
    from PyQt4 import QtCore, QtGui
    

    This needs to be done once at the beginning of your program, before the other PyQt modules are imported, and will ensure that a QVariant is never returned by any Qt API.

    0 讨论(0)
提交回复
热议问题