[PyQt] QAbstractItemModel segfaults, example code

Matt Chambers chambers at imageworks.com
Fri May 16 17:57:47 BST 2008


Tried with Qt 4.3, Qt 4.4, PyQt 4.3.3, PyQt 4.4.  I think it has 
something to do with my parent implementation.  It starts ok but if you 
try to open the tree it segfaults right away.

#!/bin/env python
import sys

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL

EMPTY_VARIANT = QtCore.QVariant()
EMPTY_INDEX = QtCore.QModelIndex()

class Item:
    def __init__(self,name,parent=None):
        self._children = []
        self.name = name
        self.parent = parent
    def children(self):
        return self._children

root = Item("root")
for i in range(1,10):
    root._children.append(Item("item%d" % i,root))

child = root._children[0]
for i in range(1,3):
    child._children.append(Item("citem%d" % i,child))

class SimpleTreeModel(QtCore.QAbstractItemModel):
    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.elements = root

    def data(self, index, role):
        if not index.isValid():
            return EMPTY_VARIANT

        e = index.internalPointer()

        if role == 0:
            return QtCore.QVariant(e.name)

        return EMPTY_VARIANT

    def index(self, row, column, parent):
        if parent.isValid():
            item = parent.internalPointer()
        else:
            item = self.elements
        return self.createIndex(row, column, item.children()[row])

    def parent(self, index):
        if not index.isValid():
            return EMPTY_INDEX
        item = index.internalPointer()
        if not item.parent:
            return EMPTY_INDEX
       
        pp = item.parent.parent
        if not pp:
            c = self.elements.children()
        else:
            c = pp.children()
        try:
            i = c.index(item.parent)
        except ValueError:
            i = 0
        return self.createIndex(i,0,item.parent)

    def rowCount(self, parent):
        if parent.isValid():
            item = parent.internalPointer()
            return len(item.children())
        else:
            print len(self.elements.children())
            return len(self.elements.children())

    def columnCount(self, parent):
        return 1


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    view = QtGui.QTreeView()
    model = SimpleTreeModel(view)
    view.setModel(model)
    view.show()
    app.exec_()



-- 
-Matt


<http://twiki.spimageworks.com/twiki/bin/view/Software/CueDevelopment> 
<http://twiki.spimageworks.com/twiki/bin/view/Software/MiddleTier>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20080516/1ff8d743/attachment-0001.html


More information about the PyQt mailing list