QML QT 后端和 GUI 设计 - 不更新对象

QML QT backend and GUI design - doesn't update the object

我有一个带有集合的简单对象,它是在 C++ 代码下创建和管理的,我想让用户查看它并从 GUI(QML - 集合的表示和 add/remove 命令)修改它,但是生命周期业务逻辑应由后端管理 (C++)

class QtModel : public QAbstractListModel {
  Q_OBJECT

 public:
  explicit QtModel(QObject *parent = nullptr);

  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
  QVariant data(const QModelIndex &index,
                int role = Qt::DisplayRole) const override;
  QHash<int, QByteArray> roleNames() const override;
  void test();

 private:
  std::vector<std::shared_ptr<Data>> collection_;
};

其中测试方法推送一个新元素:

void QtModel::test(){
  collection_.push_back(std::make_shared<Data>("test"));
}

我试过这样操作: https://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.html

而 qml 代码只获取对象的当前状态。忽略进一步的修改:

  application = std::make_unique<QGuiApplication>((int &)argc, argv);
  engine = std::make_shared<QQmlApplicationEngine>();

  qt_model_.test(); // 1 element, GUI shows 1 element
  engine->rootContext()->setContextProperty("myGlobalObject", &qt_model_);


  // those are ignored
  qt_model_.test();  // 2 elements, GUI shows 1 element
  qt_model_.test();  // 3 elements, GUI shows 1 element
  qt_model_.test();  // 4 elements, GUI shows 1 element

  application->exec();

为了演示,我使用了这样的 GridLayout:

    GridLayout {
        anchors.fill: parent
        flow:  width > height ? GridLayout.LeftToRight : GridLayout.TopToBottom
        Repeater {
            model: myGlobalObject
            delegate : Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: Style.appLightBackgroundColor
                Label {
                    anchors.centerIn: parent
                    text: model.name
                    color: Style.fontDarkColor
                }
            }
        }
    }

所以QML中的对象没有更新,而在C++中注册后才进行修改

您没有从测试函数发送 RowsInserted 信号,因此 QML 无法知道何时更新。请这样调整:

void QtModel::test(){
   beginInsertRows({}, collection_.size(), collection_.size() + 1);
   collection_.push_back(std::make_shared<Data>("test"));
   endInsertRows();
}