Search code examples
pythonpython-3.xpyqtpyqt5qsqltablemodel

QTableModel Align Headers


When subclassing a QSqlTableModel is it possible to right align the headers?

class SclDataModel(QSqlTableModel):
    def __init__(self, parent=None):
        super(SclDataModel, self).__init__(parent)
        self.setTable("scldata")
        self.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.setHeaderData(0, Qt.Horizontal, 'recordid')
        self.setHeaderData(1, Qt.Horizontal, 'svcdataid')
        self.setHeaderData(2, Qt.Horizontal, 'Receipts Start')
        self.setHeaderData(3, Qt.Horizontal, 'Receipts End')
        self.setHeaderData(4, Qt.Horizontal, 'Billing Rate')

    def headerData(self, p_int, Qt_Orientation, role=None):
        #Need to right align the headers

Solution

  • You only have to return the desired alignment when the role is requested Qt::TextAlignmentRole:

    class SclDataModel(QtSql.QSqlTableModel):
        def __init__(self, parent=None):
            super(SclDataModel, self).__init__(parent)
            self.setTable("scldata")
            self.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
            self.setHeaderData(0, QtCore.Qt.Horizontal, 'recordid')
            self.setHeaderData(1, QtCore.Qt.Horizontal, 'svcdataid')
            self.setHeaderData(2, QtCore.Qt.Horizontal, 'Receipts Start')
            self.setHeaderData(3, QtCore.Qt.Horizontal, 'Receipts End')
            self.setHeaderData(4, QtCore.Qt.Horizontal, 'Billing Rate')
    
        def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
            if role == QtCore.Qt.TextAlignmentRole and orientation == QtCore.Qt.Horizontal:
                return QtCore.Qt.AlignRight
            return super(SclDataModel, self).headerData(section, orientation, role)
    

    update:

    If you want a specific column to only filter using section, remember which section starts at 0, for example the following code only changes the alignment for the second column:

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.TextAlignmentRole and orientation == QtCore.Qt.Horizontal and section == 1:
            return QtCore.Qt.AlignRight
        return super(SclDataModel, self).headerData(section, orientation, role)