Search code examples
pythonpyqtpyqt5qtableviewqabstracttablemodel

Show certain columns in QTableView


Suppose I have QAbstractTableModel which feeds 2 QTableView. One tableview shows all data in the model. Please advise how can I approach to specify the other tableview to show only 2 columns from the same model.


Solution

  • A simple solution is to hide the columns using the hideColumn() method of QTableView.

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
    
            model = QtGui.QStandardItemModel(5, 5, self)
            for i in range(model.rowCount()):
                for j in range(model.columnCount()):
                    it = QtGui.QStandardItem("{}-{}".format(i, j))
                    model.setItem(i, j, it)
    
            table_all = QtWidgets.QTableView()
            table_all.setModel(model)
    
            table = QtWidgets.QTableView()
            table.setModel(model)
    
            for column_hidden in (0, 3, 4):
                table.hideColumn(column_hidden)
    
            lay = QtWidgets.QHBoxLayout(self)
            lay.addWidget(table_all)
            lay.addWidget(table)
    
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())