How to implement WPF-like MVVM in Qt/C++/QML?

前端 未结 1 1278
时光取名叫无心
时光取名叫无心 2021-02-05 22:35

I\'m writing a proof of concept application, that is very simple. Basically it\'s composed of a UI where a list of \"Note\" type objects is displayed in a QML ListView.

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 22:52

    I've posted a rather complete example in another answer.

    The general procedure is:

    1. Create a model that derives from QAbstractItemModel. You can reuse any of the models already provided by Qt, for example QStringListModel.

    2. Expose it to QML. E.g. use setContextProperty() of QML Engine's rootContext().

    3. The model's roles are visible in the context of the delegate in QML. Qt provides default mapping between names and roles for the DisplayRole (display) and EditRole (edit) in a default implementation of roleNames().

      delegate: Component {
          TextInput {
              width: view.width // assuming that view is the id of the view object
              text: edit // "edit" role of the model, to break the binding loop
              onTextChanged: model.display = text // "display" role of the model
          }
      }
      
    4. You can create intermediate viewmodels, if needed, by attaching proxy models between the views and the backend models. You can derive from QAbstractProxyModel or one of its subclasses.

    0 讨论(0)
提交回复
热议问题