how can `setData` method fail?

Viewed 107

Documentation for QAbstractItemModel.setData, which I've reproduced below, says that the method should return true if successful or false otherwise. My question is the following: How can this method not be successful?

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

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.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also Qt::ItemDataRole, data(), and itemData().

2 Answers

The objective of the return value of setData() is to indicate whether or not the information associated with the role and the QModelIndex was edited, and it will depend on the developer if it returns true or false.

Some examples that illustrate the above:

  • If you want your model to be non-editable (which by default is any model) then always return false.

  • If you want only some items to be editable or not so you will return true or false depending on the item.

  • If you want the new value to meet certain restrictions. A practical example could be if the items to edit must be ages, so for negative values it must return false, and for the other cases true.

The method is in an abstract class and can be overridden. If it is overwritten, anything can happen in that new implementation, right?

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

So it's not only possible it will be overridden, it's even necessary in some cases. What "successful" means is up to the implementer of the overriding method, and it can return either true or false.

Related