Search code examples
pyqtqtreeviewqabstractitemmodel

PyQt: QTreeView and QAbstractItemModel in human language


While diving deep into TreeView/Model concept here is what I "understand" so far...

First I subclass MyTreeView() class where I extend a QTreeView build-in by assigning it to MyOwnAbstractItemModel() model (subclassing in a next step):

class myTreeView(QTreeView):
    def __init__(self, parent=None):
        super(myTreeView, self).__init__(parent)
        self.myOwnAbstractModel = MyOwnAbstractItemModel()
        self.setModel(self.myOwnAbstractModel)

I continue with subclassing/describing MyOwnAbstractItemModel(). It uses a built-in QAbstractItemModel() class as a "template" to start with...

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

From what I understand there are some MyOwnAbstractItemModel() methods that must be declared for MODEL to work. I wonder where could I get a complete list of those method() names and their syntax description?

I looked at the code examples posted online. It appears those pre-defined methods have a specific syntax already pre-defined... such as number of incoming arguments and what type of arguments is expected... for example the method below dosen't get any incoming arguments (not clear what a purpose of it):

def mimeTypes(self):
    #print '\n mimeTypes(self)'
    types = QStringList()
    types.append('application/x-ets-qt4-instance')
    return types

But this method:

def dropMimeData(self, mimedata, action, row, column, parentIndex):
    parentNode = self.nodeFromIndex(parentIndex)

takes four arguments. Please advice! Many thanks in advance.


Solution

  • If you download the source code for PyQt, you will find a model-testing module in the contrib/pymodeltest directory. This module provides a way to check for the common errors found in custom model implementations. You may find it useful to look through the code in this module, as it has a lot of helpful comments that explain the purpose of many of the tests it performs.

    Also, you should read through the Model/View Programming overview in the Qt Docs - in particular the Model Subclassing reference.