PyQt5: Setting data for a QStandardItem

白昼怎懂夜的黑 提交于 2019-12-25 08:05:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!