简体   繁体   中英

qml set text property from c++

I'm creating a quick application using qt-creator .qml file:

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 :

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

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

Also, keep in mind that reaching from C++ into QML is almost always bad design. It's OK if you are just trying stuff out, but in actual production the correct practice is to connect QML to C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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