[PyQt] QTreeView and custom QStandardItemModel loses its Python counterparts

David Aguilar davvid at gmail.com
Mon Apr 29 21:41:46 BST 2013


We're seeing a change in behavior in the latest PyQt4.

We have a custom QStandardItemModel with custom QStandardItems.  It is being
used by a QTreeView.

When calling tree.invisibleRootItem().child(i) we are getting back
QtGui.QStandardItem instances instead of our custom classes.

This seemed related to a previous problem (but this one is different):

http://thread.gmane.org/gmane.comp.python.pyqt-pykde/25027/focus=25028


We are using the latest sip (4.14.6) and PyQt4 (4.10.1).

Qt is version 4.8.2 (version-locked due to a 3rd-party dependency).

We're on RHEL 6.4, Python 2.6.6.


I've pasted our test case below.  Older versions of PyQt4 would print the
Python object (PPNavigationItem) instead of QtGui.QStandardItem when
clicking on the items.

This seems like a bug.  Is there anything else we can do to help?

Your help is very much appreciated.

--- >8 --- test.py --- >8 ---
#!/usr/bin/env python

import sys
from PyQt4 import QtGui


class PPNavigationItem(QtGui.QStandardItem):

    def __init__(self, name=None):
        QtGui.QStandardItem.__init__(self)
        if name is None:
            self.setText("None")
        else:
            self.setText(name)


class PPNavigationModel(QtGui.QStandardItemModel):

    def __init__(self, parent=None):
        QtGui.QStandardItemModel.__init__(self)

    def initializeAll(self):
        self.clear()
        parentItem = self.invisibleRootItem()
        for name in ["abc", "def", "ghi"]:
            item = PPNavigationItem(name)
            parentItem.appendRow(item)

class PPNavigationTree(QtGui.QTreeView):

    def __init__(self, parent = None):
        QtGui.QTreeView.__init__(self)

        self.setAllColumnsShowFocus(True)
        self.header().hide()

class PPNavigationWidget(QtGui.QWidget):

    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self)
        self.buildWidget()

    def buildWidget(self):
        mainLayout = QtGui.QVBoxLayout()
        self.setLayout(mainLayout)

        # set up view/model
        self.view = PPNavigationTree(self)
        self.model = PPNavigationModel(self)
        self.model.initializeAll()
        self.view.setModel(self.model)

        mainLayout.addWidget(QtGui.QLabel("Click on item"))
        mainLayout.addWidget(self.view)

        self.view.clicked.connect(self.foo)

    def foo(self, index):
        root = self.model.invisibleRootItem()
        for i in range(root.rowCount()):
            item = root.child(i)
            if not item:
                continue
            print item


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    widget = PPNavigationWidget()
    widget.show()
    sys.exit(app.exec_())



More information about the PyQt mailing list