QML元素ID访问从C 访问

qml element id access from c++

本文关键字:访问 ID 元素 QML      更新时间:2023-10-16

在C 方面我写了此代码

    :::::::::::::
    QMetaObject::invokeMethod(rootObject,"changeText",Q_ARG(QVariant,"txt1"),
Q_ARG(QVariant,"hello"))

在qml侧我写了这篇

Text {
  id: txt1
  text: "hi"
}
function changeText(id,str){
        id.text=str
}

ChangEtext函数在QML侧起作用,但是当我从C 侧调用它时,它不起作用。我认为CPP侧方法将" TXT1"发送为QString,因此ChangEtext函数不起作用。

你能告诉我我该怎么做?

从C 更改QML对象的属性的正确方法是在C 中获取该对象,而不是Call SetProperty()方法。例子:QML:

Rectangle
{
  id: container
  width: 500; height: 400
  Text {
    id: txt1
    objectName: "text1"
    text: "hi"
  }
}

请注意,您必须添加用于获取孩子的对象名称属性。在此示例中,矩形是rootObject。然后在C 中:

QObject *rootObject = dynamic_cast<QObject*>(viewer.rootObject());
QObject *your_obj = rootObject->findChild<QObject*>("text1");
your_obj->setProperty("text", "500");

您可以将其压缩到这样的一行呼叫:

viewer.rootObject()->findChild<QObject*>("text1")->setProperty("text", "You text");

一种替代方法是使用您之前的方法,但将对象名称命名为 ChangEtext 方法,并通过主要对象的孩子进行迭代,直到找到您感兴趣的一种方法:

Rectangle {
  id: container
  width: 500; height: 400
  Text {
    id: txt1
    objectName: "text1"
    text: "hi"
  }
  function changeText(objectName,str){
    for (var i = 0; i < container.children.length; ++i)
      if(container.children[i].objectName === objectName)
      {
        container.children[i].text = str;
      }
  }
}