简体   繁体   中英

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

I have implemented the QAbstractItemModel as a tree structure. It is working fine, but for my next step I need to be able to get the QModelIndex of a node, but I'm not sure how to do that.ö

This is my TreeModel

    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()

And this is the Node class which I'm using with the TreeModel

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)

I can create nodes and add them to the model like this

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

Now I need to know the QModelIndex of, for instance, node . I would like to be able to do it like this

node_index = model.getIndexOf(node)

But I have no idea how to implement this.


The solution was fairly simple. I just need to call

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

and pass this index to insertRow() .

I also found an error in 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调用类似的model.index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM