Question

I can't get QComboBox::findData to work properly in my PyQt application.

It seems as if PyQt doesn't compare QVariant's with Python tuples properly, causing Qt not to find my tuples. Example follows:

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

a = Qt.QApplication([])

cb = Qt.QComboBox()
cb.addItem("Bah", (1,2))
cb.addItem("Foo", (3,4))

print cb.findData((1,2))
print cb.findData((3,4))

print cb.itemData(0)
print cb.itemData(1)

print cb.findData(cb.itemData(0))
print cb.findData(cb.itemData(1))

With api=2 (auto-convert QVariant<->python) it does not find anything and I get the following output:

-1
-1
(1, 2)
(3, 4)
-1
-1

With api=1 (no auto-convert), it only finds it in the latter (useless) case:

-1
-1
<PyQt4.QtCore.QVariant object at 0x02FBF148>
<PyQt4.QtCore.QVariant object at 0x02FBF148>
0
1

Any idea how to get the first case working (findData with new tuples, and auto-convert QVariant) ?

(Using PyQt 4.8.3, SIP 4.12.1 and Qt 4.6.1)

Was it helpful?

Solution

From @ekhumoru's comment above, replacing the tuples with lists is a suitable workaround: (my epmhasis)

This is probably more of a limitation rather than a bug. Behind the scenes, PyQt has to attempt conversion of Python types for certain operations. Obviously, not all combinations of type/operation are supported. Mutability seems to be one limiting factor. If the tuples are exchanged for lists, the above example code will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top