QSQLTableModel中的格式设置值出现问题

时间:2018-10-31 12:36:50

标签: python python-3.x pyqt pyqt5

子类化QSQLTableModel并覆盖数据方法:

class SclDataModel(QSqlTableModel):
    def __init__(self, parent=None):
        super(SclDataModel, self).__init__(parent)

    def data(self, index, role=None):
        if role == Qt.DisplayRole:
            if index.column() == 2 or index.column() == 3:
                val = QSqlTableModel.data(self, index, Qt.DisplayRole) #<--Is set to None on cell edit.
                print('Value={}'.format(val))   
                return '${:,.2f}'.format(val)
            else:
                return super(SclDataModel,self).data(index,role)
        elif role == Qt.TextAlignmentRole:
            return Qt.AlignVCenter | Qt.AlignRight
        else:
            return QVariant()

加载表时,这些值正确呈现;但是,当我编辑其中一项时,出现格式为NoneType的值格式错误。奇怪的是,当我插入新行并编辑值时,它的格式正确。

enter image description here

如果我编辑此值,则会出现以下错误:

Value=None
Traceback (most recent call last):
  File "/mnt/DevServer/Python/PPSBooks/SvcData/scldata_browse.py", line 39, in data
    return '${:,.2f}'.format(val)
TypeError: unsupported format string passed to NoneType.__format__

1 个答案:

答案 0 :(得分:1)

通常不建议修改模型,因为它代表数据,并且在您的情况下,符号$仅是可视的,因此可视任务是委托的:

class MoneyDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(MoneyDelegate, self).initStyleOption(option, index)
        option.text = '${:,.2f}'.format(index.data())
        option.displayAlignment = Qt.AlignVCenter | Qt.AlignRight

...

view = QTableView()
delegate = MoneyDelegate(view)
for i in (2, 3):
    view.setItemDelegateForColumn(i, delegate)

另一方面,如果您要修改数据,则默认角色为Qt::DisplayRole

class SclDataModel(QSqlTableModel):
    def data(self, index, role=Qt.DisplayRole):
        ...

更新:如果要修改编辑器,必须覆盖委托的createEditor()方法:

class MoneyDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(MoneyDelegate, self).initStyleOption(option, index)
        option.text = '${:,.2f}'.format(index.data())
        option.displayAlignment = Qt.AlignVCenter | Qt.AlignRight

    def createEditor(self, parent, option, index):
        editor = super(MoneyDelegate, self).createEditor(parent, option, index)
        if any(isinstance(editor, t) for t in (QDoubleSpinBox, QSpinBox)):
            editor.setMinimum(0)
            editor.setMaximum(2**15)
        return editor