Qt C++程序和qml的交互方法

来源:互联网 发布:空知猩猩 编辑:程序博客网 时间:2024/06/05 08:26

更新:黑莓开发者网站上的文章非常好!!C++ and QML integration

================================================================

以下代码在Qt creator中测试过。


================================================================

    //方法1:

    //1.1 通过setContextProperty()暴露已存在的Qt C++对象给QML
    //1.2 qml中可以直接使用myObjectExposeByCxProperty对象
cpp文件:
MyClass myObj;
    myObj.setmyString("Hello World");
    
    QDeclarativeEngine *engine=viewer.engine();
    QDeclarativeContext *context=engine->rootContext();
    context->setContextProperty("myObjectExposeByCXProperty", &myObj);


    qml文件:
onClicked: label.text=myObjectExposeByCXProperty.myString;

    

注意:在BlackBerry 10 Cascades中,设置context property的方法稍有不同。

QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);

setContextProperty("myObjectExposeByCXProperty", &myObj);


类的方法需要声明为 Q_INVOKABLE 的,比如头文件中声明如下,这样才能在qml中调用这个类的play()方法。
Q_INVOKABLE void play();
================================================================
    //方法2:
    //2.1 通过setContextProperty()暴露已存在的Qt C++对象给QML
    //2.2 qml接受cpp程序发过来的信号
cpp文件:
MyClass myObj;
    myObj.setmyString("Hello World");
    
    QDeclarativeEngine *engine=viewer.engine();
    QDeclarativeContext *context=engine->rootContext();
    context->setContextProperty("myObjectExposeByCXProperty", &myObj);


    qml文件:
    Connections
    {
        target: myObjectExposeByCXProperty
        onMyStringChanged:label.text="你好!Signal handler received, thanks man"
    }


================================================================
    //方法3:注册类型
    //3.1 注意main.cpp需要#include <QtDeclarative>
//3.2 qml中可以直接声明使用MyClass类型
    cpp文件:
qmlRegisterType<MyClass>("RegisterMyType", 1, 0, "MyClassType");


qml文件:
import RegisterMyType 1.0


onClicked: myclassExposeByRegType.setmyString("xxx");
               label.text=myclassExposeByRegType.myString;


    MyClassType
    {
        id:myclassExposeByRegType

    }


提示:BlackBerry官方的一个例子,节略。。。

To use Phone APIs in QML, register the classes in your main.cpp file:

qmlRegisterType<bb::system::phone::Phone>("bb.system.phone", 1, 0, "Phone");bb::data::DataSource::registerQmlTypes();

http://developer.blackberry.com/cascades/documentation/device_comm/phone/index.html





原创粉丝点击