0

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?

1 Answer 1

1

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.

1
  • 1
    this worked very well, thank you! but it appeared I only needed the QCustomTableWidgetItem class, the other one wasn't neccessary as I'm adding these custom ...Items to a regular table and don't have to delcare new one anywhere.
    – adamczi
    Commented Aug 31, 2016 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.