python - 为什么我的 QListView 在 IconMode 中是空的?

标签 python qt qt4 pyqt pyside

我有一个 QListView 显示来自自定义 ListModel 的数据。在“常规” View 模式 (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)

    # ...

最佳答案

经过大量调试后,我发现 data() 从未被调用过。问题在于我将数据插入模型的方式:应该调用 beginInsertRows()endInsertRows()。新方法类似于以下内容:

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

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

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

关于python - 为什么我的 QListView 在 IconMode 中是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337466/

相关文章:

c++ - 如何在目录中添加所有 .pri 文件

python - 未安装 PyQt5 模块 "QtQuick"

QTableView : change precision for double values

Qt 无模式对话框销毁

python - Python SSH服务器(twisted.conch)命令过滤和端口转发

python - 基于jupyter笔记本创建项目

python - 如何在 TensorFlow 中索引稀疏张量?

python - Mypy 因重载和文字而失败

regex - QRegExp如何匹配连续的unicode?

qt - 将槽调用设为虚函数