I'm new to Blackberry 10 development. I've created simple BB 10 cascades project.
I want to change the text of a label through c++ function.
main.qml
import bb.cascades 1.0
Page {
content: Container {
id: containerID
Button {
id: button1
objectName: "button"
text: "text"
onClicked: {
btnClicked("New Label Text");
}
}
Label {
id: label1
objectName: "label1"
text: "Old Label Text"
}
}
}
Now in which file i've to declare and in which file i've to define the function btnClicked(QString) function.
HelloBB.hpp
// Default empty project template
#ifndef HelloBB_HPP_
#define HelloBB_HPP_
#include
namespace bb { namespace cascades { class Application; }}
class HelloBB : public QObject
{
Q_OBJECT
public:
HelloBB(bb::cascades::Application *app);
virtual ~HelloBB() {}
};
#endif
HelloBB.cpp
// Default empty project template
#include "HelloBB.hpp"
#include
#include
#include
using namespace bb::cascades;
HelloBB::HelloBB(bb::cascades::Application *app) : QObject(app)
{
// create scene document from main.qml asset
//set parent to created document to ensure it exists for the whole application lifetime
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
qml->setContextProperty("app", this);
// create root object for the UI
AbstractPane *root = qml->createRootObject();
// set created root object as a scene
app->setScene(root);
}
Now I want to change the label text from Old Label Text to the user given text. I'm calling the c++ function from qml. I don't know where to define this function and how to connect this c++ function from qml.
Thanks.
解决方案
As a cliff's notes:
In your HelloBB constructor you can expose the class to the QML like so:
qml->setContextProperty("HelloBB", this);
And then create a method in the C++ that you will be able to call from the QML. Remember, the method has to be marked as Q_INVOKABLE to be called from the QML.
Consider this:
In HelloBB.hpp:
public:
Q_INVOKABLE void test();
In HelloBB.cpp:
void HelloBB::test() {
qDebug() << "TEST";
}
In main.qml:
onClicked: {
HelloBB.test ()
}