Christian
Christian

Reputation: 105

Calls to data() in a QAbstractListModel

I'm trying to learn Qt's model-view architecture and I'm wondering how come, in the following code, data() is continuously called when editing an item after double-clicking on it?

In this mockup, it's not really a problem as it's a simple five-item list, but Qt seems to lookup the data for all the row/columns in the model continuously. Is this expected behavior, or am I missing some piece of code which avoids so there's no extra and potentially expensive calls to the file/object with the data which the model makes accessible to views?

I'm using PyQt4 v4.8.2 if it makes a difference. Thanks in advance!

from PyQt4 import QtCore, QtGui

class Model(QtCore.QAbstractListModel):

    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.table = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
        self.i = 0

    def setData(self, index, value, role = QtCore.Qt.EditRole):
        value = QtCore.QVariant.toPyObject(value)
        print "setData:",value

        row = index.row()
        self.table[row] = value

        self.emit(QtCore.SIGNAL("dataChanged( const QModelIndex&, const QModelIndex& )"), index, index)
        return True

    def rowCount(self,parent):
        return 5

    def flags(self, index):
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled

    def data(self,index,role):
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            row = index.row()
            self.i = self.i + 1
            print self.i
            return self.table[row]

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)

    m = Model()

    view = QtGui.QListView()
    view.setModel(m)
    view.show()

    view2 = QtGui.QTableView()
    view2.setModel(m)

    view.show()
    view2.show()
    app.exec_()
    sys.exit()

Upvotes: 0

Views: 930

Answers (2)

TonyK
TonyK

Reputation: 17124

This might be just the debugger. When your breakpoint is reached, if the debugger paints over your list view, then it will get redrawn as soon as you continue execution. Try keeping the debugger and the list view separate from each other on the screen, and see if this changes anything.

Upvotes: 0

Jeffrey Jose
Jeffrey Jose

Reputation: 2052

I believe everytime Qt redraws your GUI (say user scrolls up and down, brings window into focus etc) Qt would redraw and that's when it would call .data()

Upvotes: 1

Related Questions