问题
If I construct a QStandardItem
like so:
item = QtGui.QStandardItem('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())
and I will get the number 123
. How can I get the number to actually display in the cell?
回答1:
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)
or:
item.setText(str(123))
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))
来源:https://stackoverflow.com/questions/42194649/pyqt5-setting-data-for-a-qstandarditem