Search code examples
pythonpyqtqtreeviewqabstractitemmodel

PyQt example editabletreemodel.py crashes when the last row is removed


In the editabletreemodel.py example (from PyQt examples/itemviews folder) I noticed that when the last row is removed (e.g. the one reading 'Connection Editing Mode' or any other after that) the application crashes with

'IndexError: list index out of range'.

Could that be because the example keeps TreeItem objects when indexes are created, etc. instead of ids? I have very similar problem and just wondered whether it is better to keep ids instead of objects? Or it is safe to check whether a row over the limit is requested like this:

def child(self, row):
    if row >= self.childCount():
        return None

    return self.childItems[row]

I use Python version 2.7.9 and PyQt version '4.9.6'.

Thanks in advance.


Solution

  • This should be reported as a bug on the pyqt mailing-list.

    The original Qt example and declares childItems as:

    QList<TreeItem*> childItems;
    

    and defines the child() function as:

    TreeItem *TreeItem::child(int number)
    {
        return childItems.value(number);
    }
    

    This doesn't do any explicit bounds-checking, because value() will simply return null if number is out of bounds. But obviously python lists don't behave in the same way, and so an explicit bounds-check is required:

    def child(self, row):
        if 0 <= row < self.childCount():    
            return self.childItems[row]