3

我有一个QListView来自自定义的显示数据ListModel。在“常规”视图ListMode模式IconMode

这是相关的代码。我省略了主窗口和任何其他杂物,但如果有帮助,我会包括它。

# Model
class TheModel(QtCore.QAbstractListModel):
    def __init__(self, items = [], parent = None):
        QtCore.QAbstractListModel.__init__(self, parent)

        self.__items = items

    def appendItem(self, item):
        self.__items.append(item)

        # item was added to end of list, so get that index
        index = len(self.__items) - 1

        # data was changed, so notify
        self.dataChanged.emit(index, index)

    def rowCount(self, parent):
        return len(self.__items)

    def data(self, index, role):
        image = self.__items[index.row()]

        if role == QtCore.Qt.DisplayRole:
            # name
            return image.name

        if role == QtCore.Qt.DecorationRole:
            # icon
            return QtGui.QIcon(image.path)

        return None

# ListView
class TheListView(QtGui.QListView):
    def __init__(self, parent=None):
        super(Ui_DragDropListView, self).__init__(parent)
        self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
        self.setIconSize(QtCore.QSize(48, 48))
        self.setViewMode(QtGui.QListView.IconMode)

    # ...
4

1 回答 1

3

经过一些繁重的调试,我发现它data()永远不会被调用。问题在于我将数据插入模型的方式:beginInsertRows()并且endInsertRows()应该被调用。新方法类似于以下内容:

def appendItem(self, item):
    index = len(self.__items)

    self.beginInsertRows(QtCore.QModelIndex(), index, index)
    self.__items.append(item)
    self.endInsertRows()

尽管旧方法不使用 using beginInsertRows()and endInsertRows(),但ListMode效果很好。这就是让我失望的原因:我仍然认为它不应该奏效。怪癖?

于 2012-11-14T11:32:13.777 回答