Qt : setData method in a QAbstractItemModel

后端 未结 3 883
星月不相逢
星月不相逢 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:16

    I couldn't find much info on this. That said, this forum post by a "Qt Specialist" suggests that this behavior is a design choice by the Qt developers:

    http://qt-project.org/forums/viewthread/31462

    More specifically, the views do not lose your input if it gets rejected by the model. This may seem weird in the context of the tutorial you are following (where the color changes out of sync with the model), but in some contexts this might be desirable.

    As an example, let's say you have designed a form using QLineEdits and QDataWidgetMapper to map the contents of the form to your model. Let's also suppose that QDataWidgetMapper::SubmitPolicy is set to AutoSubmit. In AutoSubmit mode, every time the QLineEdit is edited and then loses focus, the model is updated. If the model also rejects the change, and the current data (sans change) is repopulated into the QLineEdit, this would have the effect of the user having to start over (rather than fixing up their entry).

    The alternative design choice is to allow the view to be out of sync with the model and, if this is undesirable, to push the responsibility to change this behavior onto the programmer.

    Two ways that I can think of off-hand to change this behavior would be to:

    1. Create a custom delegate that handles setData -> false by emitting a custom dataRejected signal that the view could connect to and use to update itself.
    2. Create a "stateless" view for your model: force the view to retrieve data from the model any time it updates itself. In this manner, submitting a potential change to the model will not update the view unless that model emits a dataChanged signal, in which case the view will retrieve current state and update itself.

提交回复
热议问题