QTableModel 对齐 Headers

QTableModel Align Headers

当对 QSqlTableModel 进行子类化时,是否可以右对齐 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

您只需 return 在请求角色时进行所需的对齐 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)

更新:

如果您希望特定列仅使用部分进行过滤,请记住哪个部分从 0 开始,例如以下代码仅更改第二列的对齐方式:

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)