QTreeView的QAbstractItemModel:我做错了什么?

时间:2017-03-02 11:18:06

标签: qt model pyqt qabstractitemmodel

我想创建一个QAbstractItemModel的子类,以便在QTreeView中使用它。起初,我决定制作一个没有支持任何层次结构的简约模型。它应该为2×3表提供简单的文本数据(只读一个)。

唉,它没有崩溃,但没有显示任何数据:只有几个列标题(1,2)。不能有人告诉我,我做错了什么?

import os, sys

from PyQt5 import QtWidgets, QtCore, QtGui, QtSvg

from PyQt5.QtCore import QPointF, QRectF
from PyQt5.QtWidgets import QGraphicsItem


from gui.graphic_items import *



class MegaModel(QtCore.QAbstractItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._root_item = 7.40
        pass

    def columnCount(self, parent_index):
        if parent_index.isValid():
            return 0
        else:
            return 2

    def rowCount(self, parent_index):
        if parent_index.isValid():
            return 0
        else:
            return 3

    def data(self, index, role):
        if index.isValid():
            return QtCore.QVariant("Oy vey!")
        else:
            return None

    def index(self, row, column, parent=QtCore.QModelIndex()):
        print("index", row, column, parent)

        if parent.isValid():
            print("valid")
            return parent.internalPointer()
        else:
            print("invalid")
            return self.createIndex(row, column, self._root_item)

    def parent(self, index):
        return QtCore.QModelIndex()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)


    mega_view = QtWidgets.QTreeView()

    mega_model = MegaModel()

    mega_view.setModel(mega_model)

    mega_view.show()

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

两个错误:

  1. 您不应该从SELECT "id", "post", "replyId" FROM "posts" AS "post" WHERE "post"."id" = 1; 方法返回parent.internalPointer() - 此方法不会返回模型的存储值,而是仅将索引返回到模型项
  2. index方法中,您为所有角色返回data。你应该只为QtCore.QVariant("Oy vey!")返回这个,对于其他角色,可以返回QtCore.Qt.DisplayRole

    None