简体   繁体   English

QML从C ++设置文本属性

[英]qml set text property from c++

I'm creating a quick application using qt-creator .qml file: 我正在使用qt-creator .qml文件创建一个快速的应用程序

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MenuBar {
           Menu {
               title: "File"
               MenuItem {  objectName: "buttonTest"
                   text: "Open"
              onTriggered: m.open()}

               MenuItem { text: "show data"
                   onTriggered: m.data()
                  }
               MenuItem { text: "Close"
                   onTriggered: Qt.quit()}
           }

       }


    Text {
            id: name
            text: qsTr("no of vertices :")
        }
    Text
    {

        text: "..........."
        objectName: "textObject"

    }
    }

I want to set text property of "textObject" from a method in c++ class I tried the following code : 我想通过尝试以下代码的c ++类中的方法设置“ textObject”的文本属性:

void Mine::data()
{
QQmlApplicationEngine engine;
 QObject *rootObject = engine.rootObjects().first();
   QObject *qmlObject = rootObject->findChild<QObject*>("textObject");

     qmlObject->setProperty("text", "Text from C++");

}

but it shows the following error: ASSERT: "!isEmpty()" in file /usr/include/qt5/QtCore/qlist.h, line 345 但是它显示以下错误:ASSERT:文件/usr/include/qt5/QtCore/qlist.h,第345行中的“!isEmpty()”

any help please? 有什么帮助吗?

The engine you are using has nothing in it, it is quite literally created on the spot and hasn't loaded anything, thus the root object list is empty. 您正在使用的引擎没有任何内容,它是从字面上直接创建的,并且没有加载任何内容,因此根对象列表为空。

You will need to reference the qml engine you are actually using for your QML code. 您将需要引用实际用于QML代码的qml引擎。 The one created in main.cpp , so you will have to pass and keep a pointer to it in classes that use it outside of main. main.cpp创建的一个,因此您必须在main之外使用它的类中传递并保留指向它的指针。

Also, keep in mind that reaching from C++ into QML is almost always bad design. 另外,请记住,从C ++到QML几乎总是不好的设计。 It's OK if you are just trying stuff out, but in actual production the correct practice is to connect QML to C++. 如果您只是尝试一些东西,那没关系,但是在实际生产中,正确的做法是将QML连接到C ++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM