[PyQt] Problem with QVariant float arguments
Baz Walter
bazwal at gmail.com
Thu Oct 25 15:05:20 BST 2018
On 24/10/2018 17:10, Phil Thompson wrote:
> On 15 Oct 2018, at 1:47 pm, Baz Walter <bazwal at gmail.com> wrote:
>>
>> There seems to be a problem when passing python floats above a certain size to Qt methods which take a QVariant argument. Could there be some kind of truncation taking place? My test set up: python 3.7.0, qt 5.11.2, sip 4.19.13, pyqt 5.11.3, gcc 8.2.1 20180831.
>>
>> Here is a test script:
>>
>> from PyQt5 import QtCore, QtGui, QtWidgets
>>
>> a = QtWidgets.QApplication(['test'])
>>
>> x0 = 1.001
>> x1 = 1.002
>> x2 = 1523015317.001
>> x3 = 1523015317.002
>>
>> m = QtGui.QStandardItemModel(); r = QtCore.Qt.UserRole
>> i = QtGui.QStandardItem('0'); i.setData(x0, r); m.appendRow(i)
>> i = QtGui.QStandardItem('1'); i.setData(x1, r); m.appendRow(i)
>> i = QtGui.QStandardItem('2'); i.setData(x2, r); m.appendRow(i)
>> i = QtGui.QStandardItem('3'); i.setData(x3, r); m.appendRow(i)
>
> Adding...
>
> v = i.data(r)
> print(v, type(v))
>
> ...shows the expected value, ie. the conversion seems to be working. That suggests it is a Qt problem?
>
I ported my test to C++ and found that the assert fails there, too. The
problem seems to be in the way Qt chooses to compare FP values. It first
tests using (a == b), and then if that fails it returns the result of
qFuzzyCompare(a, b) instead. Now of course comparing FP values using
only the equals operator is never reliable, but in the above example the
irony is that equals actually gets it right and qFuzzyCompare gets it wrong:
>>> 1523015317.001 == 1523015317.000
False
>>> QtCore.qFuzzyCompare(1523015317.001, 1523015317.000)
True
Anyway, it seems the Qt devs are already aware that QVariant comparisons
can be generally problematic (depending on the underlying types), so I
don't think I'll bother pursuing this any further. The easiest
work-around in the above example is to simply use string-based matching
instead of variant-based matching. But I suppose that also must have its
limitations when comparing floats (fortunately all my values have a
fixed precision).
More information about the PyQt
mailing list