QTableWidget Integer

11,126

You were on the right track. Your code doesn't work because you're not calling the QTableWidgetItem's setData() function but trying to assign it a value. You have

item.setData = (Qt.DisplayRole,intValue)

instead of

item.setData(Qt.DisplayRole,intValue)

Also, when reading the data back it's not just the location that's shown but the data itself as a QVariant. You should find that item.data(Qt.DisplayRole).toString() will return your data back as a string by converting the QVariant (via its .toString() method).

Here's a quick working example just to demonstrate:

import sys
from PyQt4.QtGui import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout
from PyQt4.QtCore import Qt

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.widget_layout = QVBoxLayout()
        self.table_widget = QTableWidget(101, 1)
        self.table_widget.setSortingEnabled(True)

        self.widget_layout.addWidget(self.table_widget)
        self.setLayout(self.widget_layout)

        for num in xrange(101):
            item = QTableWidgetItem()
            item.setData(Qt.EditRole, num)
            self.table_widget.setItem(num, 0, item)


if __name__ == '__main__':
  app = QApplication(sys.argv)
  widget = Widget()
  widget.show()
  sys.exit(app.exec_())
Share:
11,126
Paul Nelson
Author by

Paul Nelson

CAD Support engineer at Micron Tech

Updated on June 10, 2022

Comments

  • Paul Nelson
    Paul Nelson about 2 years

    I am trying to insert and display integers in my QTableWidget. They don't display. It works if I convert everything to strings, but then I can't sort columns numerically--only lexically (1, 10, 100, etc.). This is using PyQt.

    I've tried some of the suggested solutions, using QTableWidgetItem.setData(someRole,intValue), bu then nothing at all displays. I've tried, Qt.UserRole, DisplayRole and Edit Role. (I don't understand why these Roles are needed to display integers, but have just followed the examples). My specific code is:

        item = QTableWidgetItem()
        item.setData = (Qt.DisplayRole,intValue)
        myTable.setItem(row, column, item)
    

    The following code works, but for strings only:

        item = QTableWidgetItem(str(intValue))
        myTable.setItem(row, column, item)
    

    Also, the suggestions for reading the data back, only show the object location, not the actual data. Example, using Eric as an interpreter shell:

    item.data(Qt.DisplayRole)

    Response: PyQt4.QtCore.QVariant object at 0x1f01fa60

    or this:

    item.data(Qt.EditRole).data()

    Response: sip.voidptr object at 0x1e904a80

    Any insight is appreciated.

  • Paul Nelson
    Paul Nelson over 11 years
    It works!! Thanks Gary. Though I'm still not sure what the Roles have to do with this working correctly.
  • Mustafa Uçar
    Mustafa Uçar about 6 years
    @GarryHughes Is it possible give them float?