Qt : setData method in a QAbstractItemModel

Ilyes Ferchiou picture Ilyes Ferchiou · Dec 26, 2013 · Viewed 8k times · Source

I'm new to model view and I have been following this tutorial while checking the documentation at the same time and I stumbled upon this little detail : The code of the tutorial which can be downloaded here has in the QAbstractItemModel class (here QAbstractListModel) the setData method which code is :

def setData(self, index, value, role = QtCore.Qt.EditRole):
    if role == QtCore.Qt.EditRole:

        row = index.row()
        color = QtGui.QColor(value)

        if color.isValid():
            self.__colors[row] = color
            self.dataChanged.emit(index, index)
            return True
    return False

According to the explanations in the tutorial and from what I understood from the documentation, if the function returns True, then the view is updated, if it returns false, nothing happens, but when I changed the code to :

def setData(self, index, value, role = QtCore.Qt.EditRole):
    if role == QtCore.Qt.EditRole:

        row = index.row()
        color = QtGui.QColor(value)

        if color.isValid():
            self.__colors[row] = color
            self.dataChanged.emit(index, index)
            return False # This is what I changed in the code
    return False

I realized that the view still gets updated if color.isValid() even if the function returns False. Am I misunderstanding the return role in the setData method or is it a bug ?

For reference, I'm using PySide 1.2.1, not PyQt4.

Answer

ekhumoro picture ekhumoro · Dec 26, 2013

To quote from the video tutorial regarding setData:

...this function needs to return true if the operation was successful, or else the view will not update itself.

Strictly speaking, this statement is false. The documentation for QAbstractItemModel only says that setData returns true if the data was set successfully, and false otherwise; it does not mention what the consequences of this might be. Specifically, it does not mention anything about updating the view.

Looking at the Qt source code, the return value of setData does get checked in a few places, and some of those checks can sometimes help trigger an update. But there are literally dozens of things that can trigger an update, so the return value of setData is in no way essential for updating items.

Perhaps it would have been more accurate to say that setData should return true, otherwise the view may not update itself (under certain circumstances).