子类化 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。奇怪的是,当我插入新行并编辑值时,它的格式正确。
如果我编辑此值,则会收到以下错误:
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/