qml 定义函数,如何从QML调用C ++函数并更改标签文本

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 ()

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值