[PySide] QModelIndex does not keep the internalPointer alive

Goswin von Brederlow goswin-v-b at web.de
Thu Jun 11 12:59:06 CEST 2015


Hi,

I have an QAbstractItemModel that realy is abstract. The model does
not have persistant objects for every row since data for the model is
stored sparse in 3 tables in mysql:

Users Table: id, name, real name, email, info
Roles Table: id, name, description
Users2Roles: id, user_id, role_id

Users can be assigned to roles by adding a pair of user id and role id
in the Users2Roles table. A user belongs to all the roles for which
such a pair exist and doesn't belong to any other roles.

>From that I'm building a tree that has all the users as top level
items and each user has all the roles as children. The
QtCore.Qt.CheckStateRole then shows if the user belongs to the rules
or not. Setting the QtCore.Qt.ItemIsUserCheckable flag also allows
(only for admins) assigning roles to users with a simple click.

Now to the problem:
-------------------

As said the model is abstract and doesn't have one object per row.
That would require user * roles many objects and most users don't have
(many) roles and only one user is ever shown in the view at any one
time (using QDataWidgetMapper to map the selected user). Due to that I
wanted to store the relevant user_id and role_id in the QModelIndexes
internalPointer and then lookup the required informations in the 3
database tables as needed.

So for the top level items (users) the index is created as:

     self.createIndex(row, column, [user_id])

and for the children (roles):

     self.createIndex(row, column, [user_id, role_id])

And there starts the problem. The generated QModelIndexes are
emidiatly corrupted. Right after the createIndex call the internal
pointer points to a list containing [..., b'\n'] (actual print()
output, not my abreviation). Later accessing the list elements in the
models data() method causes a segfault.

My guess is that the QModelIndex does not register the python object
with the GC when it stores it in the underlying c++ class and the
object gets trashed by the GC.

So my question is:

How can I store non persistant python objects in a QModelIndex?

MfG
	Goswin



More information about the PySide mailing list