Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot access QML object in C++ code

i'm working on a QML application (blackberry 10) and have a QML file like this:

import bb.cascades 1.0    
Page {
        content: Container {
            id: containerID
            Button {
                id: button1
                text: "text"
                onClicked: {
                }
            }
            Label {
                id: label1
                text: "text"
            }
        }
    }

now i want to access the label1 in my c++ code, so i have the following code:

#include "app.hpp"

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>

using namespace bb::cascades;

App::App()
{
    QmlDocument *qml = QmlDocument::create("main.qml");
    //-- setContextProperty expose C++ object in QML as an variable
    //-- uncomment next line to introduce 'this' object to QML name space as an 'app' variable
    //qml->setContextProperty("app", this);

    AbstractPane *root = qml->createRootNode<AbstractPane>();

    QObject *labelTest = root->findChild<QObject*>("label1");
    if (labelTest)
        labelTest->setProperty("text", "yes!!");

    Application::setScene(root);
}

now i run the app, but the text of the label does not change.

what is wrong?

like image 957
gurehbgui Avatar asked Sep 18 '12 18:09

gurehbgui


1 Answers

I found the answer by myself. the QML code:

import bb.cascades 1.0

//-- create one page with a label and text

Page {
    property alias labelText: label.text      
    content: Container {            
        Label {
            id: label
            text: "Label"
        }  

        Button {
            objectName: "button"
            text: "Button"
        }                               
    }
}

and the c++ code:

#include "app.hpp"

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>

using namespace bb::cascades;

App::App()
{
    QmlDocument *qml = QmlDocument::create("main.qml");
    //-- setContextProperty expose C++ object in QML as an variable
    //-- uncomment next line to introduce 'this' object to QML name space as an 'app' variable
    //qml->setContextProperty("app", this);

    AbstractPane *root = qml->createRootNode<AbstractPane>();

    root->setProperty("labelText", "yes");

    QObject *newButton = root->findChild<QObject*>("button");
    if (newButton)
        newButton->setProperty("text", "New button text");

    Application::setScene(root);
}
like image 88
gurehbgui Avatar answered Sep 23 '22 13:09

gurehbgui