QTableWidget Integer

前端 未结 1 1206
既然无缘
既然无缘 2020-12-09 13:45

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

相关标签:
1条回答
  • 2020-12-09 14:35

    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_())
    
    0 讨论(0)
提交回复
热议问题