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

QTableView - where to get model?



  • I want to implement a simple table view to which my program would then export data from a text file to show. However, after making a window with QTableView in Qt Designer there is only a blank white space and nothing like a table. Can you please help me with the following:

    • How does one set a model for QTableView? Where does that model come from?
    • How does one export data to QTableView cells after they are created?

    Would appreciate your help.



  • Use

    data = TableData()
    table.setModel(data)
    

    where data derives from QAbstractTableModel e.g.

    class TableData(QAbstractTableModel):
        def __init__(self, parent: QObject = None):
            super().__init__(parent)
    
        # The number of rows to display
        def rowCount(self, parent: QModelIndex = QModelIndex()):
            return 3
    
        # The number of columns to display
        def columnCount(self, parent: QModelIndex = QModelIndex()):
            return 3
    
        # Return the data you want to display in the table (could be stored e.g. in a list of tuples)
        def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> object:
            if role == Qt.DisplayRole:
                return index.row() * 10 + index.column()
            return None
    

Log in to reply