Stacked
Stacked

Reputation: 861

PyQt4.QtCore.QVariant object instead of a string?

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')
indx = self.combox_widget.currentIndex()
print self.combox_widget.itemData(indx)

however, I get <PyQt4.QtCore.QVariant object at 0x02AC1A70> on trying to retrieve the DATA value ('Green' in the example above). What am I missing here?

Upvotes: 4

Views: 6961

Answers (1)

ekhumoro
ekhumoro

Reputation: 120598

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.

Upvotes: 12

Related Questions