PyQt4 - 如何获取模型元素的 QModelIndex

PyQt4 - How to get the QModelIndex of an element of a model

我已经将 QAbstractItemModel 实现为树结构。它工作正常,但下一步我需要能够获取节点的 QModelIndex,但我不确定该怎么做。ö

这是我的树模型

    class TreeModel(QtCore.QAbstractItemModel):

        """ Subclassing the QAbstractItemModel to create
            a hierarchical data model
        """

        def __init__(self, root, parent=None):
            """ Initialization method """
            super(TreeModel, self).__init__(parent)
            self._rootNode = root

        def columnCount(self, parent):
            """ Returns the number of columns """
            return 2


        def rowCount(self, parentIndex):
            """ Returns the number of rows """
            if not parentIndex.isValid():
                parentNode = self._rootNode
            else:
                parentNode = parentIndex.internalPointer()

            return parentNode.childCount()


        def getNode(self, index):
            """ Returns the node at the given index """
            if index.isValid():
                node = index.internalPointer()
                if node:
                    return node
            else:
                return self._rootNode


        def insertRow(self, position, parentIndex, node):
            """ Insert rows into parent """

            if not parentIndex.isValid():
                return False
            else:
                parentNode = self.getNode(parentIndex)
                print parentNode

            self.beginInsertRows(parentNode, position, position+1)
            success = parentNode.insertChild(position, node)
            self.endInsertRows()

            return success


        def data(self, index, role):
            """ Returns the requested data """
            if not index.isValid():
                return None

            node = index.internalPointer()

            if role == QtCore.Qt.DisplayRole:
                return dict_data[index.column()](node)


        def headerData(self, section, orientation, role):
            """ Returns a string to be displayed in the header """
            if role == QtCore.Qt.DisplayRole:
                return dict_headers[section]


        def parent(self, index):
            """ Returns the parent of the node at index """
            node = index.internalPointer()
            parentNode = node.parent()

            # Return empty index if parent is root
            if parentNode == self._rootNode:
                return QModelIndex()
            # Create and return an index if parent is not root
            else:
                return self.createIndex(parentNode.position(), 0, parentNode)


        def index(self, position, column, parentIndex):
            print "---"
            print position, column, parentIndex
            print "---"

            """ Returns the index of the element at the given position and column """
            if not parentIndex.isValid():
                parentNode = self._rootNode
            else:
                parentNode = parentIndex.internalPointer()

            childItem = parentNode.child(position)

            if childItem:
                return self.createIndex(position, column, childItem)
            else:
                return QModelIndex()

这是我与 TreeModel

一起使用的节点 class
class Node(object):

    """ Class that supplies basic TreeNode functionalities """

    def __init__(self, name="None", parent=None):
        """ Initialization method """

        self._name = name
        self._children = []
        self._parent = parent

        if parent is not None:
            assert type(parent) == Node or Node_Packetlist
            parent.addChild(self)


    def name(self):
        """ Returns the name of this node """
        return self._name


    def rowExists(self, position):
        """ Checks whether the given position exists in this node """
        return 0 <= position <= self.childCount()


    def addChild(self, child):
        """ Returns the children of this node """
        self._children.append(child)


    def insertChild(self, position, child):
        """ Inserts a child at the given position in this node """
        if self.rowExists(position):
            self._children.insert(position, child)
            child._parent = self
        else:
            return False

    def removeNode(self, node):
        """ Removes a node from this nodes children """
        if type(node) == Node and node.parent() == self:
            nodeRow = node.position()
            self.removeChild(nodeRow)
        else:
            return False

    def removeChild(self, position):
        """ Removes the node located at the given position """
        if self.rowExists(position):
            child = self._children.pop(position)
            child._parent = None
        else:
            return False


    def child(self, position):
        """ Returns child at given position """
        if self.rowExists(position):
            return self._children[position]
        else:
            return False


    def children(self):
        """ Returns all children of this node """
        return self._children
QTimer can only be used with threads started with QThread

    def childCount(self):
        """ Returns number of children this node has """
        return len(self._children)


    def parent(self):
        """ Returns the parent node of this node """
        return self._parent


    def position(self):
        """ Returns the position at which this node is located in the parent node """
        if self._parent is not None:
            return self._parent._children.index(self)

我可以像这样创建节点并将它们添加到模型中

root = Node("root")
node = Node("node", root)
model = TreeModel(root)
treeView = QTreeView()
treeView.setModel(model)

现在我需要知道 node 的 QModelIndex。 我希望能够这样做

node_index = model.getIndexOf(node)

但我不知道如何实现它。


解决方案相当简单。我只需要打电话

node_index = self.model.createIndex(
             0,
             0,
             self.node) 

并将此索引传递给 insertRow()

我在insertRow()

中也发现了一个错误
def insertRow(self, position, parentIndex, node):
    """ Insert rows into parent """
        if not parentIndex.isValid():
            return False
        else:
            parentNode = self.getNode(parentIndex)
            print parentNode

        # first argument of beginInsertRows needs to be a QModelIndex,
        # not a node
        #                        V
        self.beginInsertRows(parentIndex, position, position+1)
        success = parentNode.insertChild(position, node)
        self.endInsertRows()

        return success

如果您有 node 的路径,那么您可以在 model.index.

中调用类似的操作