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.
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.
For data method it is clear; it checks every time the role state and there are 8-15 different roles.
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)
The only way to answer this question would be to get the Qt source code for QAbstractItemModel
and QAbstractListModel
, and create a call graph for the rowCount
function. I image it would be quite extensive, because Qt will call rowCount
every time it needs to do any kind of bounds-checking operation. Needless to say, this means there is not going to be a simple explanation for how rowCount
will be used for any particular program.
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 abstractions . If you want to learn how they really work, you should read the Model/View Programming Overview (particularly the Model Subclassing Reference ).
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.