3

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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
NineTails
  • 550
  • 4
  • 24
  • `item.setData(str(123))`. – ekhumoro Feb 13 '17 at 00:27
  • I need it to be an editable number though, and I can't rely on string to float conversions. I don't understand why if I set data directly from the model: `model.setData(model.index(0,1),123.987)` it will show the number, but if I do it on a `QStandardItem` it won't. – NineTails Feb 13 '17 at 00:33
  • Also I just tried your suggestion, and it does not work either. Do you want me to paste a runnable example program? I just thought it might be too much for the question if it was a simple answer. – NineTails Feb 13 '17 at 00:35
  • 1
    Forgot the role: `item.setData(str(123), QtCore.Qt.DisplayRole)` (which is the same as `item.setText(str(123))`). But also see [this answer](http://stackoverflow.com/a/41860415/984421). – ekhumoro Feb 13 '17 at 01:10
  • You are a legend. So basically the data is there but to display it has to be displayed as a `QString`, which is done by specifying the role when setting the data. The role being the type of data you are assigning to the item (tooltip/display etc.) If you are happy to write this as an answer I will accept it. – NineTails Feb 13 '17 at 01:19

1 Answers1

5

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))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336