程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了QML QT 后端和 GUI 设计 - 不更新对象大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决QML QT 后端和 GUI 设计 - 不更新对象

开发过程中遇到QML QT 后端和 GUI 设计 - 不更新对象的问题如何解决?下面主要结合日常开发的经验,给出你关于QML QT 后端和 GUI 设计 - 不更新对象的解决方法建议,希望对你解决QML QT 后端和 GUI 设计 - 不更新对象有所启发或帮助;

我有一个带有集合的简单对象,它是在 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++中注册后发生的

解决方法

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

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

大佬总结

以上是大佬教程为你收集整理的QML QT 后端和 GUI 设计 - 不更新对象全部内容,希望文章能够帮你解决QML QT 后端和 GUI 设计 - 不更新对象所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。