Python PyQt5 - How to rename table headers?

1.4k Views Asked by At

I have a function that adds new column to the table, hoewer I do not know how to rename the column header. What I want is for the user to either double click on the column header so that you could edit the column header. or what I have now: I have a a button that adds a new column and line Edit where you write your column name.

I do not know how to rename the column header names

This is my code that handles adding new column to the table.

    def addNewColumn(self):
    self.tableColumn =  self.table_Database.columnCount()   
    self.table_Database.setColumnCount(self.tableColumn + 1)
    self.table_Database.setItem(0,self.tableColumn,QtWidgets.QTableWidgetItem())

    if self.table_Database.rowCount() == 0:
        self.table_Database.setRowCount(1)
        self.table_Database.setItem(1,0,QtWidgets.QTableWidgetItem())
2

There are 2 best solutions below

0
Aftershock On BEST ANSWER

if you use a model.. See headerData... it defines the horizontal header... columns.

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data

    def headerData(self, p_int, Qt_Orientation, role=None):
        if role == Qt.DisplayRole and Qt_Orientation==Qt.Horizontal:
            header = ['Symbol', 'Time', 'Price', 'Current Price','Orig Qty', 'Executed Qty', 'Type']
            return header[p_int]
        else:
            return QtCore.QAbstractTableModel.headerData(self, p_int, Qt_Orientation, role)



    def data(self, index, role):
        if role == Qt.DisplayRole:
            # See below for the nested-list data structure.
            # .row() indexes into the outer list,
            # .column() indexes into the sub-list
            return self._data[index.row()][index.column()]

    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])
0
Filip Studený On

SOLUTION/FIX: So here is the fix, I have also added an error message that will be displayed if the column doesn't carry a name, if it doesn't the column will not be added

 def addNewColumn(self):
    self.error_message = QtWidgets.QErrorMessage()
    if self.addNewColumnName_TEXT.text() == '':
        self.error_message.showMessage('Column doesn't have a name')
    else:
        self.tableColumn =  self.table_Database.columnCount()         
        self.table_Database.setColumnCount(self.tableColumn + 1)
        self.table_Database.setItem(0,self.tableColumn,QtWidgets.QTableWidgetItem())
        
        self.__tableHeader_Labels.append(self.addNewColumnName_TEXT.text())
        self.table_Database.setHorizontalHeaderLabels(self.__tableHeader_Labels)