Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set the QTableView header name in Pyqt4

I want to know how can i set the custom header names in QTableview

when i create a QTableview i get the column and row header names as 1,2,3,4. I want to know how can i set my own column and header titles.


I got the solution as required, Hope it could help some one who comes across the same situation

like image 365
Rao Avatar asked Jan 03 '13 08:01

Rao


2 Answers

If you're using a QTableView with your own model you need to implement the headerData() method in the model to return data for the header. Here's a snippet to show just column headings - change the header_labels value to change the header text.

class TableModel(QAbstractTableModel):

    header_labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4']

    def __init__(self, parent=None):
        QAbstractTableModel.__init__(self, parent)

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return self.header_labels[section]
        return QAbstractTableModel.headerData(self, section, orientation, role)
like image 188
Gary Hughes Avatar answered Sep 16 '22 21:09

Gary Hughes


The original poster produced the following code as a solution (orginally posted in a pastebin link that was deleted by a moderator):

from PyQt4 import QtCore, QtGui

class myWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)
        self.centralwidget  = QtGui.QWidget(self)
        self.view           = QtGui.QTableView(self.centralwidget)
        self.view.setSortingEnabled(True)
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.addWidget(self.view, 1, 0, 1, 3)

        self.setCentralWidget(self.centralwidget)

        self.model = QtGui.QStandardItemModel(self)

        for rowName in range(3) * 5:
            self.model.invisibleRootItem().appendRow(
                [   QtGui.QStandardItem("row {0} col {1}".format(rowName, column))
                    for column in range(3)
                    ]
                )
        for column in range(3):
            self.model.setHeaderData(column, QtCore.Qt.Horizontal,
                                      'Column %d' % int(column+1))
            for row in range(3 * 5):
                self.model.setHeaderData(row, QtCore.Qt.Vertical,
                                            'Row %d' % int(row+1))

        self.proxy = QtGui.QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.model)

        self.view.setModel(self.proxy)

if __name__ == "__main__":
    import sys

    app  = QtGui.QApplication(sys.argv)
    main = myWindow()
    main.show()
    main.resize(400, 600)
    sys.exit(app.exec_())
like image 44
talonmies Avatar answered Sep 16 '22 21:09

talonmies