PyQt4 how does model gets executed?
<p>I am trying to understand PyQt4 model views. I have built simple list model view. Then I used âstepâ variable to see how the model gets executed.</p>

<p>What I canât understand is: why every time the new loop gets executed, rowCount method gets called 5 times, and from then every 2 times? It is independent from how many items I have in the list.</p>

<p>For data method it is clear; it checks every time the role state and there are 8-15 different roles. </p>

<pre><code>from PyQt4 import QtGui, QtCore, uic
import sys

step = 0
class ModelOne(QtCore.QAbstractListModel):

    global step
    step += 1
    print(step, 'init')

    def __init__(self, colors = [], parent = None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self.__colors = colors

     def rowCount(self, parent):           
        global step
        step += 1
        print(step, 'rowCount')

        return len(self.__colors)

    def data(self, index, role):            
        global step
        step += 1
        print(step, 'data')      

        if role == QtCore.Qt.DisplayRole:           
            row = index.row()
            value = self.__colors[row]
            return value

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    listView = QtGui.QListView()
    listView.show()
    model = ModelOne(['black', 'white'])
    listView.setModel(model)
    sys.exit(app.exec_())


OUTPUT

loop 1    
1 init
2-6 rowCount    (5 steps)
7-14 data       (8 steps)
15 rowCount
16 rowCount
17-24 data      (8 steps)
25 rowCount
26 rowCount
27-34 data      (8 steps)

loop 2   
35-40 rowCount   (5 step)
41-55 data       (15 step)
56 rowCount
57 rowCount
58-72 data       (15 step)
</code></pre>

<p>The only way to answer this question would be to get the Qt source code for <code>QAbstractItemModel</code> and <code>QAbstractListModel</code>, and create a call graph for the <code>rowCount</code> function. I image it would be quite extensive, because Qt will call <code>rowCount</code> every time it needs to do any kind of bounds-checking operation. Needless to say, this means there is <strong>not</strong> going to be a simple explanation for how <code>rowCount</code> will be used for any particular program.</p>

<p>But in any case, I don't think tracing the execution of a model is a good way to try to understand it. Models need to be understood as <em>abstractions</em>. If you want to learn how they really work, you should read the <a href="http://doc.qt.io/qt-4.8/model-view-programming.html" rel="nofollow">Model/View Programming Overview</a> (particularly the <a href="http://doc.qt.io/qt-4.8/model-view-programming.html#model-subclassing-reference" rel="nofollow">Model Subclassing Reference</a>).</p>

python pyqt4 model-view