[PyQt] Item data on QTreeView

Diego diego.no.spam at gmail.com
Sun Jul 8 23:02:27 BST 2012


Hi,

I have a QTreeView widget that displays one Message per row. It also
has several columns, each of which displays one Message's attribute.
The tree's model is a QStandardItemModel that I populate this way:

for m in messages:
    items = []
    it = QStandardItem()
    it.message = m     # (1) See here
    it.setData(m.headers['Subject'], Qt.DisplayRole)
    it.setCheckable(False)
    items.append(it)

    it = QStandardItem()
    it.message = m    # (2) See here
    it.setData(m.headers['From'], Qt.DisplayRole)
    items.append(it)

    it = QStandardItem()
    it.message = m    # (3) See here
    it.setData(m.headers['Date'], Qt.DisplayRole)
    items.append(it)

    tree_view.model().appendRow(items)


When a row is selected in the QTreeView, I need to be able to access
the object whose attributes are being displayed in that row. I don't
know how to properly do that, and the only thing that worked for me is
to store the original object in each and every item I create, as in
(1), (2) and (3) in the code snippet above. It appears to me as a very
inefficient way of solving this problem and I think there must be a
much better solution for it.

So my question is: how do I store the original Message object in every
row in order to get access to it when the user selects that row?

Thanks in advance,
Diego


More information about the PyQt mailing list