[PyQt] returning numpy numbers in QVariant

Phil Thompson phil at riverbankcomputing.com
Fri Apr 23 13:57:53 BST 2010


On Tue, 20 Apr 2010 22:35:03 +0100, Jeremy Sanders
<jeremy at jeremysanders.net> wrote:
> Hi - some of my code has stopped working after upgrading to PyQt 4.7. It 
> seems numbers in numpy arrays used to convert okay to QVariant types, but

> now they seem to produce blank results:
> 
> import sys
> from PyQt4.QtCore import *
> from PyQt4.QtGui import *
> import numpy
> 
> class Model(QAbstractTableModel):
>     
>     def columnCount(self, parent):
>         return 1
> 
>     def rowCount(self, parent):
>         return 100
> 
>     def data(self, index, role):
>         if role == Qt.DisplayRole:
>             a = numpy.array([index.row()*0.1])
>             return QVariant(a[0])
>         else:
>             return QVariant()
> 
> if __name__ == "__main__":
>     app = QApplication(sys.argv)
>     win = QTableView()
>     mod = Model()
>     win.setModel(mod)
>     win.show()
>     app.exec_()
> 
> 
> This should show a list of numbers in the QTableView. It did and does not

> any longer.
> 
> Is this a bug or shouldn't I be doing this?

Are numpy numbers regular ints/floats or are they a sub-class specific to
numpy?

QVariant has been changed (over time) to make sure that no information is
lost when converting from and to the original object. So an int sub-class
will stay as a Python object and will not get converted to a C++ int.

If this is the problem then the fix is to explicitly convert the numpy
number to a base Python type before converting to a QVariant...

    return QVariant(float(a[0]))

...and this will work for older versions as well.

Phil


More information about the PyQt mailing list