【问题标题】:QML QT backend and GUI design - doesn't update the objectQML QT 后端和 GUI 设计 - 不更新对象
【发布时间】:2021-07-15 13:46:19
【问题描述】:

我有一个带有集合的简单对象,它是在 C++ 代码下创建和管理的,我想让用户从 GUI 中查看和修改它(QML - 集合的表示和添加/删除命令),但生命周期和业务逻辑应该由后端管理(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++ 中注册后发生的

【问题讨论】:

  • 别忘了问一个问题 :)

标签: c++ qt qml


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多