如何为连接到QListView的SQL模型选择行

3 投票
1 回答
1226 浏览
提问于 2025-04-16 00:54

我在用PyQt4做一个项目,后端用的是SQLAlchemy,目的是为QListView创建一个模型。

我最开始的版本是这样的:

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

这个版本有个问题,就是一旦我开始删除行,ID就不再是连续的了。

所以我现在的解决方案是这样的:

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

不过我觉得这样做可能会在后面选择数据库中正确的条目时遇到麻烦。

有没有什么更好的方法呢?我最初的想法是从数据库中返回最大的ID作为行数,然后用一些虚假的数据填充那些不存在的行,并在视图中把它们隐藏起来。因为这个应用最多也就需要处理大约1万条数据,而这已经是非常不可能的情况了,我觉得这样做是可行的。

1 个回答

1

把行的ID存放在模型中的一个列表里,然后用这个列表来获取数据库中的行。如果你想在模型和视图之间实现排序,只需要按照需要对这个列表进行排序就可以了。

如果你直接从数据库中删除了一行,模型就不知道这个变化,所以视图不会更新。这样的话,视图里会显示过时的数据,用户在尝试编辑那些已经不存在的行时可能会出问题,这样就会很糟糕。你可以通过在每次进行这种操作时调用模型的reset()方法来刷新所有的视图,从而解决这个问题。

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

撰写回答