Monday, May 13, 2013

Signals and slots in QML

As like our previous discussion on Signals and slots mechanism, we will follow the same example with a different approach. Approach in the sense, making the signal and slot mechanism work from QML.

Our example output will be like : 



Upon button click signal, change label text

T

The completed mechanism is done in QML. The QML file will look like:

import bb.cascades 1.0

Page {
    Container {
        Button {
            id: myButton
            text : "emit signal"
            horizontalAlignment: HorizontalAlignment.Left
            signal buttonClicked(string text)   //  declare signal
            onClicked: {
                myButton.buttonClicked.connect(label.changeText);   //  connect signal and slot
                myButton.buttonClicked("Button Clicked")    //  Call slot.
            }
        }   //  end button
        Label {
            id: label
            horizontalAlignment: HorizontalAlignment.Right
            text: "Im a label"
            function changeText(text) {
                label.text = text;
            }
        }   //  end label
    }   //  end contianer
}   //  end page

Here comes the detailed explanation in 4 steps :

1)In Button, I'm declaring the signal for the buttonclick.

signal buttonClicked(string text)   //  declare signal

2)Write a slot function to listen the signal.

function changeText(text) {
                label.text = text;
            }

3) Connect the signal and slot.

 myButton.buttonClicked.connect(label.changeText);   //  connect signal and 

4) Call slot method

myButton.buttonClicked("Button Clicked")    //  Call slot.


By this way, we can use signals and slots mechanism from QML.

No comments:

Post a Comment