python - QSQLTableModel 中的格式化值出现问题

标签 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__

最佳答案

一般来说,不建议修改模型,因为它代表数据,并且在您的情况下,符号 $ 仅是可视的,因此可视化任务是委托(delegate)的:

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):
        ...

更新:如果要修改编辑器,则必须覆盖委托(delegate)的 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

关于python - QSQLTableModel 中的格式化值出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083492/

相关文章:

Python:禁用 iptcinfo 警告

python - 替换列表中的所有负值

python - 如何从 MIDI 文件中提取单个和弦、休止符和音符?

python - 如何在 PyQT 中分离 ui 和实现?

python - flask 在运行时不读取 bootstrap.css (mac)

python - 在python中解压每个文件夹和子文件夹中的所有.bz2文件

python - numpy nanmean 错误

python - PyQt - 通过滚动条链接多个 QTableView 对象

python - 动画不更新

c++ - 解决这个网络爬行任务的最简单方法是什么?