Saturday, January 12, 2013

Signal Slot connection with C++ object and Cascades QML

In this blog post I shown how to achieve signal slot connection with QML and C++ object using Connections QML element.

In BB10 Cascades there are two ways to achieve the same.

First using java script connect method, like blow. Following code is from my previous post of Sprite animation.

This is preferred method as we are using only Cascades API.

Here timer is exported c++ object. By using timer.timeout.connect(renderNextFrame) statement. We are connecting the timeout signal of timer C++ object to renderNextFrame function.

import bb.cascades 1.0
...
        Container {
            id: sprite;
            horizontalAlignment: HorizontalAlignment.Center
            verticalAlignment: VerticalAlignment.Center
            layout: AbsoluteLayout {}  
            
            onCreationCompleted: {
                timer.timeout.connect(renderNextFrame);
                timer.start(200);
            }
                      
            function renderNextFrame() {
                ...
            }
       }
...

Second, Using Connections element like below.
import bb.cascades 1.0
import QtQuick 1.0
...
        Container {
            id: sprite;
            horizontalAlignment: HorizontalAlignment.Center
            verticalAlignment: VerticalAlignment.Center
            
            onCreationCompleted: {
                timer.start(200);
            }
            
            attachedObjects: [
                Connections {
                    target:timer;
                    onTimeout:{
                        sprite.renderNextFrame();
                    }
                }
            ]
            
            function renderNextFrame() {
             ...
            }
        }
...
To use Connections element, we need to import QtQuick components, as Connections element is part of QtQuick.

Once its imported, you will need to declare Connections element as part of attachedObjects. Then you can use it as usual in QML.

And just for reference, I create Timer object like below for above example.
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);

    QTimer* timer = new QTimer(app);
    qml->setContextProperty("timer",timer);

No comments:

Post a Comment