views:

73

answers:

1

I am trying the following in PyQt4, using SQLAlchemy as the backend for a model for a QListView.

My first version looked like this:

class Model(QAbstractListModel):
     def __init__(self,  parent=None,  *args):
        super(Model,  self).__init__(parent,  *args)

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

        if role == QtCore.Qt.DisplayRole:
            d = sqlmodel.q.get(index.row()+1)
            if d:
                return d.data
        return None

This had the problem that as soon as I start deleting rows, the ids are not consecutive anymore. So my current solution looks like this:

class Model(QAbstractListModel):
     def __init__(self,  parent=None,  *args):
        super(Model,  self).__init__(parent,  *args)

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

        if role == QtCore.Qt.DisplayRole:
            dives = Dive.q.all()
            if index.row() >= len(dives) or index.row() < 0:
                return None
            return dives[index.row()].location

But I guess this way, I might run into trouble selecting the correct entry from the database later on.

Is there some elegant way to do this? My first idea would be to return the maximum id from the db as the row_count, and then fill non-existing rows with bogus data and hide them in the view. As the application will, at most, have to handle something around 10k, and that is already very unlikely, I think this might be feasible.

A: 

Store the row IDs in a list in the model and use that as an index to retrieve the database rows. If you want to implement sorting within the model-view system just sort the list as reqired.

If you delete a row from the database directly, the model won't know and so it won't update the views. They will display stale data and possibly also break things when users try to edit rows that nolonger exist in the underlying database, which could get realy bad. You can get round this by calling reset() on the model whenever you do this to refresh all the views.

class Model(QAbstractListModel):
     def __init__(self,  parent=None,  *args):
        super(Model,  self).__init__(parent,  *args)
        self.id_list = []

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

        row_id = self.id_list[index.row()]

        if role == QtCore.Qt.DisplayRole:
            # query database to retrieve the row with the given row_id
Simon Hibbs