开发者

qtreeview data inconsistency

开发者 https://www.devze.com 2023-04-10 18:02 出处:网络
I have a QTreeView GUI based on editabletreemode.py in the PyQt examples. Inside the model, I re-implemented setData() for my need: for some out-of-bound value, I\'m returning False, otherwise, it ret

I have a QTreeView GUI based on editabletreemode.py in the PyQt examples. Inside the model, I re-implemented setData() for my need: for some out-of-bound value, I'm returning False, otherwise, it returns True

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

    item = self.getItem(index)
    result = item.setData(index.column(), value)

    if result:
        self.dataChanged.emit(index, index)
        self.modified = True

    print "setData() returning ", result
    return result

Problem is, even when setData is returning False, GUI still accepts the changed value. So I now have inconsistent data between the model and view. What would make sense to me is that when setData() return False to reject the value, view should revert back to old value. Is this possible?

[SOLVED] Actually the return value of setData() doesn'开发者_如何学Ct seem to matter. The QTreeView seem to call data() to re-retrieve the value afterwards anyway. The problem I was having was because setData() changed the internal data even though it returned False.

If somebody could explain to me what is the return value of setData() is used for, that'd be great.


The only issue I can see is the signature of .setData(), which is .setData(index, value, role). Neither your code snippet nor the description of your problem are verbose enough to say anything else.

Edit: Indeed, after looking at the Qt sources, I stand corrected. Unlike I've stated before this edit, the return value of .setData() is not actually used by the view.

The data is committed to the model by .setModelData() of the delegate. Normally, Qt uses a QStyledItemDelegate, whose .setModelData() method actually ignores the return value of .setData(). Thus the view does indeed not care for whether the data was successfully set. When the editor for a cell in the view is closed, the view just displays whatever is now the value of that cell (as retrieved by .data()).

However, the return value of .setData() is still important, and well-behaving models should take care to return a proper value. Models generally abstract data sources, and are in and by themselves independent from views. Thus models are also accessed directly, and in this case, the caller needs to check the return value of .setData() to know, whether the operation was successful.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号