[PyKDE] QModelIndex and PyQT
Andreas Pakulat
apaku at gmx.de
Wed May 24 23:17:35 BST 2006
On 24.05.06 16:39:28, Allen Bierbaum wrote:
> I apologize if this has been discussed here before, I searched the
> mailing list and didn't find anything.
Not here, but PyQt4 ships with examples that show you how you can
achieve what you want.
In short that is: keep a dict of id->obj around and use
createIndex(row,col, id) to attach the id of the obj to the index. You
can retrieve the id via internalId() function of the object.
Part of simpletreemodel.py:
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
item = self.object_dict[index.internalId()]
return QtCore.QVariant(item.data(index.column()))
def index(self, row, column, parent):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = self.object_dict[parent.internalId()]
childItem = self.object_dict[parentItem.child(row)]
if childItem:
return self.createIndex(row, column, id(childItem))
else:
return QtCore.QModelIndex()
> make things limp along. I am currently funneling all index lookups
> through a manually maintained map from int id's to python objects. Is
> this how other people are also working with QT4 models?
Oh, you already found the "right" way...
> I was surprised that there was no way (that I know of) to attach a
> python object to a QModelIndex. It seems from the QT documentation
> that this is the intent of how indexes are to be used in C++, but
> there is no corresponding way to do this in Python.
I can imagine that using id's and a dict is much safer. The
pointer-thing needs a cast and that cast can go wrong. Maybe it's also
just not possible.
> I think it could be implemented by casting from PyObject* to void*
> behind the scenes and passing through to the existing
> internalPointer() C++ interface. This would make working in Python
> much easier while still preserving the intent of the QModelIndex
> interface.
I don't see why using internalPointer is easier than using internalId.
IMHO it doesn't matter much wether you do
item = static_cast<TreeItem*>(index.internalPointer())
or
item = self.obj_dict[index.internalId()]
I guess the latter might also be faster, because there's no need to
interface with C.
Andreas
--
You learn to write as if to someone else because NEXT YEAR YOU WILL BE
"SOMEONE ELSE."
More information about the PyQt
mailing list