Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

using strings and floats in QTableView, QStandardItemModel, QStandardItem



  • I'm trying to use a QTableView, with a QStandardItemModel. The QStandardItemModel expects QStardardItem objects to populate "table cells", and the constructor for QStandardItem only accepts QStrings, or just str in python.
    My data is both strings and floats. I noticed the documentation says you can subclass QStandardItem to "define new types for them". Here is my attempt at subclassing QStandardItem:

    from PyQt5.QtGui import QStandardItem
    class TableItemFloat(QStandardItem):
        def __init__(self, val):
            super().__init__(str(val))
            return
        
        def type(self):
            return 1000
    

    But this clearly isn't what I'm meant to do. Do I need to reimplement setData() ? Do I need to have a instance attribute like self.data = val? What about setItem() the model uses? Do I need to subclass the model too? Here is what I'm experimenting with:

    class Example(QWidget):
        
        def __init__(self):
            super().__init__()
            
            self.setGeometry(300, 300, 400, 300)
            self.setWindowTitle("QTableView")
            self.initData()
            self.initUI()
            
        def initData(self):
        
            #data = [['1','2',3, 'None'],["blue", "green", "yellow", "red"]]
            data = [[1,2,3],[4,3,5]]
            self.model = QStandardItemModel(10, 6)
            
            row = 0
            col = 0
            
            for i in data:
                for j in i:
                    print(j)
                    item = TableItemFloat(j)
                    self.model.setItem(row, col, j)
                    row = row + 1
                col = col +1
                row = 0
                
        def initUI(self):
                 
            self.tv = QTableView(self)
            self.tv.setModel(self.model)
            vbox = QVBoxLayout()
            vbox.addWidget(self.tv) 
            self.setLayout(vbox)  
    
    app = QApplication([])
    ex = Example()
    ex.show()
    sys.exit(app.exec_())
    

Log in to reply