[PyQt] Re: problem with QAbstractItemModel
info at linos.es
Sat Nov 7 09:23:31 GMT 2009
Vicent Mas escribió:
> On 2009-11-06 Baz Walter <bazwal at ftml.net> said:
>> your implementation of QAbstractItemModel.index is going to get called
>> *a lot* and in many unforseen ways.
> Yes, but it is a general fact, not something that happens to my particular
> implementation, right?
>> i think a more sane implementation
>> would be something like this:
>> def index(self, row, column, parent):
>> if self.hasIndex(row, column, parent):
>> branch = self.nodeFromIndex(parent)
>> return self.createIndex(row, column, branch.childAtRow(row))
>> return QModelIndex()
>> this fixes your immediate bug, and will probably avoid many others.
> I know that my implementation is very rough, but it is intended just for
> testing purposes. Of course your workaround and other similar (like the one
> sent by Linos) fixes the problem, but they leave the main question unanswered:
> why wrong row values are passed to the index method? Is it expected? If it is
> developers are forced to include good sanity code in their index method
> implementation (as you and Linos did), but I've not seen any reference to this
> in the Qt documentation. IMHO the Qt model implementation should not allow
> wrong row values to be passed to the index method. In fact, the example in the
> 'Editable Tree Model Example' section of the Qt documentation doesn't check at
> all the validity of the row argument passed to the index method
> On the other hand the fact that my script works fine with some Qt/PyQt versions
> but fails with recent versions seems to indicate that there is a bug either in
> the Qt implemention of models or in that PyQt versions.
> PS: Baz, thanks for your code snippet
> Share what you know, learn what you don't
in the qt examples from qt 4.5 documentation you can see they use this in the
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent)
if (!hasIndex(row, column, parent))
parentItem = rootItem;
parentItem = static_cast<TreeItem*>(parent.internalPointer());
TreeItem *childItem = parentItem->child(row);
return createIndex(row, column, childItem);
and this in the item class.
TreeItem *TreeItem::child(int row)
but they can do this because QList .value method dont get an error if it is out
T QList::value ( int i ) const
Returns the value at index position i in the list.
If the index i is out of bounds, the function returns a default-constructed
value. If you are certain that the index is going to be within bounds, you can
use at() instead, which is slightly faster.
I am using this same strategy but like i am using python list i check before if
i can return the children, you can use a "try except" too.
More information about the PyQt