Piodo
Piodo

Reputation: 616

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

I have simple object with collection which is created and managed under C++ code and I want to let user view it and modify it from GUI (QML - presentation of the collection and add/remove commands), but lifetime and business logic should be managed by backend (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_;
};

where test method push a new element:

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

I tried follow this way: https://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.html

And qml code just takes the current state of the object. The further modifications are ignored:

  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();

For presentation I am using GridLayout like this:

    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
                }
            }
        }
    }

So the object in QML is not updated, while the modifications are taken place after its registration in C++

Upvotes: 0

Views: 127

Answers (1)

Amfasis
Amfasis

Reputation: 4168

You are not sending RowsInserted signals from the test function, so QML cannot know when to update. Please adjust like so:

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

Upvotes: 1

Related Questions