2

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)

Macke
  • 24,812
  • 7
  • 82
  • 118
  • I can confirm the behavior using api=2 with PyQt 4.8.5 and sip 4.12.4. I suggest you to report a bug in the PyQt4 mailing list. – Vicent Oct 11 '12 at 12:06
  • I'm not sure how does QVariant work in PyQt but in C++ QVariant with types other than built in compares the pointer to data stored in QVariant instead of calling operator==, thats why search may not work – Kamil Klimek Oct 11 '12 at 12:26
  • 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. – ekhumoro Oct 11 '12 at 17:02
  • 1
    @ekhumoro You're right. I've asked to the PyQt4 mailing list. This is the Phil Thomson answer: It's a limitation of QVariant in that it doesn't provide an opportunity to inject a call to a Python comparison function when comparing custom types. – Vicent Oct 12 '12 at 05:56
  • @ekhumoro: Excellent workaround, thanks! – Macke Oct 12 '12 at 12:36
  • @Vicent: Thanks for getting on the mail-list, and coming back with quote from Phil. I suppose the maillist would've been a better to ask, but it googles poorly. ;-p – Macke Oct 12 '12 at 12:37

1 Answers1

2

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.

Macke
  • 24,812
  • 7
  • 82
  • 118