Qt : setData method in a QAbstractItemModel

后端 未结 3 894
星月不相逢
星月不相逢 2021-01-18 08:34

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 tut

3条回答
  •  死守一世寂寞
    2021-01-18 09:32

    Am I misunderstanding the return role in the setData method or is it a bug ?

    From the Qt documentation:

    bool QAbstractItemModel::setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) [virtual]

    Sets the role data for the item at index to value.

    Returns true if successful; otherwise returns false.

    The dataChanged() signal should be emitted if the data was successfully set.

    The base class implementation returns false. This function and data() must be reimplemented for editable models.

    Yet, you seem to emit the dataChanged() signal even if the data is not successfully set based on the return value. Also, the tutorial you seem to refer to, is using the self.__colors set in your code for the rowCount(), `data(), and other methods. If you would like to avoid the update, you will need to return False before any such statement.

    You need to pay attention to these criterias because the signal and the colors are managed internally while the return value is used by the caller to see if the setData() method had been successfully set.

    Based on the knowledge above, you should have written this code for your second attempt to make it work as you expect it 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():
                return False
        return False
    

提交回复
热议问题