QTableModel对齐标题

时间:2018-10-31 11:19:05

标签: python python-3.x pyqt pyqt5 qsqltablemodel

在子类化QSqlTableModel时,是否可以正确对齐标题​​?

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

1 个答案:

答案 0 :(得分:2)

仅在请求角色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)

更新:

如果希望特定的列仅使用section进行过滤,请记住哪个部分从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)