PyQt5:为 QStandardItem 设置数据 [英] PyQt5: Setting data for a QStandardItem
问题描述
如果我像这样构造一个 QStandardItem
:
If I construct a QStandardItem
like so:
item = QtGui.QStandardItem('Item Name')
当此项目添加到 QStandardItemModel
模型并在 QTreeView
中查看时,我得到一个显示 Item Name
的单元格.但是,当我构建一个像:
When this item is added to a QStandardItemModel
model and is viewed in a QTreeView
I get a cell that says Item Name
. However, when I construct one like:
item = QtGui.QStandardItem()
item.setData(123)
我得到一个空单元格,但我仍然可以通过调用来调用数据:
I get an an empty cell, but I can still recall the data by calling:
print(item.data())
我会得到数字123
.如何让数字实际显示在单元格中?
and I will get the number 123
. How can I get the number to actually display in the cell?
推荐答案
传递给 QStandardItem
构造函数的参数设置 DisplayRole.所以等效的方法是:
The argument passed to the QStandardItem
constructor sets the data for the DisplayRole. So the equivalent method would be either:
item.setData(str(123), QtCore.Qt.DisplayRole)
或:
item.setText(str(123))
但如果你想以原始数据类型存储数据,而不是先将其转换为字符串,你可以使用 QStyledItemDelegate
来控制原始数据的显示方式:
But if you want to store the data in its orignal data-type, rather than converting it to a string first, you can use QStyledItemDelegate
to control how the raw data is displayed:
class ItemDelegate(QStyledItemDelegate):
def displayText(self, value, locale):
if isinstance(value, float):
return '%08f' % value
return value
view.setItemDelegate(ItemDelegate(view))
这篇关于PyQt5:为 QStandardItem 设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!