插入和删除QAbstractListModel中的项目

时间:2013-06-21 08:51:42

标签: python qt pyqt4 qabstractlistmodel

我正在尝试创建一个QAbstractListView,用于QComboBox,它维护它包含的项目的排序列表。我在下面提供了一些示例代码来说明我的问题。当我更新列表中的项目时,组合框的currentIndex不会更新以反映对模型的更改。我已经尝试过使用rowsAboutToBeInserted和rowsInserted信号,但我看不出任何效果(也许我做错了?)。

我的实际用例有点复杂,但这个例子应该足够了。正在排序的项目不仅仅是字符串,需要花费更多精力进行排序,并使ItemDataRole与其DisplayRole不同。

itemsAdded和itemsRemoved是我自己的函数,它将连接到我试图代理的另一个列表中的信号。

要触发此问题,请按“插入”c“'按钮。字符串正确插入列表,但选择从“e”移动到“d”(即选择索引不会改变)。

example code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui

class Model(QtCore.QAbstractListModel):
    def __init__(self, *args, **kwargs):
        QtCore.QAbstractListModel.__init__(self, *args, **kwargs)
        self.items = []

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

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid() is True:
            if role == QtCore.Qt.DisplayRole:
                return QtCore.QVariant(self.items[index.row()])
            elif role == QtCore.Qt.ItemDataRole:
                return QtCore.QVariant(self.items[index.row()])
        return QtCore.QVariant()

    def itemsAdded(self, items):
        # insert items into their sorted position
        items = sorted(items)
        row = 0
        while row < len(self.items) and len(items) > 0:
            if items[0] < self.items[row]:
                self.items[row:row] = [items.pop(0)]
                row += 1
            row += 1
        # add remaining items to end of list
        if len(items) > 0:
            self.items.extend(items)

    def itemsRemoved(self, items):
        # remove items from list
        for item in items:
            for row in range(0, len(self.items)):
                if self.items[row] == item:
                    self.items.pop(row)
                    break

def main():
    app = QtGui.QApplication([])
    w = QtGui.QWidget()
    w.resize(300,300)
    layout = QtGui.QVBoxLayout()

    model = Model()
    model.itemsAdded(['a','b','d','e'])

    combobox = QtGui.QComboBox()
    combobox.setModel(model)
    combobox.setCurrentIndex(3)
    layout.addWidget(combobox)

    def insertC(self):
        model.itemsAdded('c')

    button = QtGui.QPushButton('Insert "c"')
    button.clicked.connect(insertC)
    layout.addWidget(button)

    w.setLayout(layout)
    w.show()
    app.exec_()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:2)

以下完整的工作示例,基于Tim的回答。

不需要调用setCurrentIndex。当正确调用insertRows / removeRows时,视图会自动跟踪此信息。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui

class Model(QtCore.QAbstractListModel):
    def __init__(self, *args, **kwargs):
        QtCore.QAbstractListModel.__init__(self, *args, **kwargs)
        self.items = []

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

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid() is True:
            if role == QtCore.Qt.DisplayRole:
                return QtCore.QVariant(self.items[index.row()])
            elif role == QtCore.Qt.ItemDataRole:
                return QtCore.QVariant(self.items[index.row()])
        return QtCore.QVariant()

    def itemsAdded(self, items):
        # insert items into their sorted position
        items = sorted(items)
        row = 0
        while row < len(self.items) and len(items) > 0:
            if items[0] < self.items[row]:
                self.beginInsertRows(QtCore.QModelIndex(), row, row)
                self.items.insert(row, items.pop(0))
                self.endInsertRows()
                row += 1
            row += 1
        # add remaining items to end of the list
        if len(items) > 0:
            self.beginInsertRows(QtCore.QModelIndex(), len(self.items), len(self.items) + len(items) - 1)
            self.items.extend(items)
            self.endInsertRows()

    def itemsRemoved(self, items):
        # remove items from the list
        for item in items:
            for row in range(0, len(self.items)):
                if self.items[row] == item:
                    self.beginRemoveRows(QtCore.QModelIndex(), row, row)
                    self.items.pop(row)
                    self.endRemoveRows()
                    break

def main():
    app = QtGui.QApplication([])
    w = QtGui.QWidget()
    w.resize(300,200)
    layout = QtGui.QVBoxLayout()

    model = Model()
    model.itemsAdded(['a','b','d','e'])

    combobox = QtGui.QComboBox()
    combobox.setModel(model)
    combobox.setCurrentIndex(3)
    layout.addWidget(combobox)

    def insertC(self):
        model.itemsAdded('c')

    def removeC(self):
        model.itemsRemoved('c')

    buttonInsert = QtGui.QPushButton('Insert "c"')
    buttonInsert.clicked.connect(insertC)
    layout.addWidget(buttonInsert)

    buttonRemove = QtGui.QPushButton('Remove "c"')
    buttonRemove.clicked.connect(removeC)
    layout.addWidget(buttonRemove)

    w.setLayout(layout)
    w.show()
    app.exec_()

if __name__ == '__main__':
    main()

答案 1 :(得分:0)

我猜您需要自己修改选择索引,例如

if row < currentIndex():
    setCurrentIndex( currentIndex() + 1 );

但您应该阅读following passage

  

为可调整大小的类似列表的数据结构提供接口的模型可以提供insertRows()和removeRows()的实现。在实现这些功能时,必须调用适当的函数,以便所有连接的视图都知道任何更改:

     

•insertRows()实现必须在将新行插入数据结构之前调用beginInsertRows(),并且必须在之后立即调用endInsertRows()。

     

•removeRows()实现必须在从数据结构中删除行之前调用beginRemoveRows(),并且必须在之后立即调用endRemoveRows()。