Changing data in an QAbstractListModel

exhuma.twn exhuma at gmail.com
Thu Sep 6 12:12:56 EDT 2007


Hi, I want to create a very simple read-only ListView. As the same
data is used on various places in the UI, I decided to create a new
ListView with a new Model instead of using the QListWidget.

So far, the data displays correctly after setting it with "setModel"
on the ListView. But how do I tell the views that the data is updated
in the model?

I defined a simple "update" method in the model which I call on
certain events to fetch the new data in the DB. I tried to "emit" the
"dataChanged()" signal of the Model without success. I don't know
where I should get the two required "index" parameters from.

Any hints?

Here's the model:
#--------------------------------------------------
class UnitListModel(QtCore.QAbstractListModel):

   __units = []

   def update(self):
      c = db_con.cursor()
      # SELECT only the most recent entry for each company
      c.execute("SELECT DISTINCT ON (unit_id) nom FROM unit ORDER BY
unit_id, year DESC")
      for unit in c.fetchall():
         self.__units.append( unit[0] )
      c.close()

   def rowCount(self, parent = QtCore.QModelIndex()):
      return len(self.__units)

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

      if index.row() >= len(self.__units):
         return QtCore.QVariant()

      if role == QtCore.Qt.DisplayRole:
         return QtCore.QVariant(self.__units[index.row()])
      else:
         return QtCore.QVariant()
#--------------------------------------------------




More information about the Python-list mailing list