[GIS] QTableView / QTableWidget alternative for floats

pyqgisqgis-plugins

Writing a QGIS plugin with PyQGIS I need a table to store and view values that are floats. I found only these two models (QTableView / QTableWidget), but they only store QString type of data, and therefore sorting of numbers gets wrong (eg. 10, 23512, 24, 35, 6874 would be correct order while it's obviously not).
Main problems that I have are:

  • Proper sorting is very important
  • Size of values stored can be any (eg. can't say it will be always 4 digits with 2 precision digits)

Is there any alternative to store numbers in tables in QGIS plugins?

Best Answer

To do this you must create a new widget derived from the QTable, and set these constraits manually.

Here is an example how to sort columns:

import sys
import random
from PyQt4 import QtCore, QtGui

class QCustomTableWidgetItem (QtGui.QTableWidgetItem):
    def __init__ (self, value):
        super(QCustomTableWidgetItem, self).__init__(QtCore.QString('%s' % value))

    def __lt__ (self, other):
        if (isinstance(other, QCustomTableWidgetItem)):
            selfDataValue  = float(self.data(QtCore.Qt.EditRole).toString())
            otherDataValue = float(other.data(QtCore.Qt.EditRole).toString())
            return selfDataValue < otherDataValue
        else:
            return QtGui.QTableWidgetItem.__lt__(self, other)

class QCustomTableWidget (QtGui.QTableWidget):
    def __init__ (self, parent = None):
        super(QCustomTableWidget, self).__init__(parent)
        self.setColumnCount(2)
        self.setRowCount(5)
        for row in range(self.rowCount()):
            self.setItem(row, 0, QCustomTableWidgetItem(random.random() * 1e4))
            self.setItem(row, 1, QtGui.QTableWidgetItem(QtCore.QString(65 + row)))
        self.setSortingEnabled(True)

If you want to set decimal precision you must do this in similar way.

Related Question