[PyQt] Item data on QTreeView

Andreas Pakulat apaku at gmx.de
Mon Jul 9 07:42:05 BST 2012


On Mon, Jul 9, 2012 at 12:02 AM, Diego <diego.no.spam at gmail.com> wrote:

> 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?

You could store it only in the first item of a row and always access it
there. Another option would be have a dict of messages and use the
row-number as key - this only works of course as long as your rows are not
re-arranged frequently.

Both approaches however duplicate some of the data though - everything
thats displayed to the user. To solve that you'd have to write your own
model subclass which directly works on the messages and returns the
corresponding data from the data() function. With such a model you could
also return the original message object when data() is called with a custom
data role.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20120709/2fc3dbf0/attachment.html>

More information about the PyQt mailing list