Hi,

2013/5/4 superpelican <superpeli...@zoho.com>:
> I'm writing a QML/Sailfish Silica app that will use the logic of a CLI C++
> application I had already written. I've also already created a QML/Silica
> UI. So I will need to let C++ and QML communicate (for example the C++ code
> has to know when a QML Button is clicked)
>
> and the C++ code will need to change the properties (for example text of a
> label) of QML items.
> [...]
> However the Sailfish example application (on which I based my app) is
> initialized differently than a normal QML application (like those on the Qt
> Docs). So does the Sailfish example application (I mean the
> sailfishapplication.cpp and main.cpp parts) create a QDeclarativeEngine
> object?

I haven't tried the Sailfish example application (just created a
fullscreen QDeclarativeView myself, which also works fine in Sailfish,
as all "themeing" / behavior is done via QML Components, anyway).

Basically, once you get ahold of a QDeclarativeView (let's say you get
a pointer "QDeclarativeView *view" to it), you can get the root
context of the view via view->rootContext() and on that you can then
set context properties using context->setContextProperty(). Ideally
you can set one QObject subclass that defines the interface between
your C++ code and QML - the QML can then interact with that object.

An example can be found here:

https://github.com/harmattan/mustr/blob/master/mustr.cpp

The "Wallpaper" object is my QObject subclass that interfaces C++ with QML:

https://github.com/harmattan/mustr/blob/master/wallpaper.h

For functions to be called from QML, they have to be slots or
Q_INVOKABLE. You can communicate back to QML with either signals or
properties. Here's how my QML looks:

https://github.com/harmattan/mustr/blob/master/mustr.qml

If you search for usages of the "wallpaper" object in there, you will
see how to call C++ functions (that fulfills your "C++ code needs to
know when a QML button was clicked" requirement):

        wallpaper.setPattern(previewPage.url)

Also, for communicating back from C++, you can connect to signals of
that object:

        Connections {
            target: wallpaper
            onDone: infoBanner.show()
        }

Another example that also shows usage of properties and might be an
even better example of interfacing existing C++ code with QML is here:

https://github.com/harmattan/classicprintqml/blob/master/ClassicPrintDeclarative.h

I've found it easiest to have one single instance of a QObject
subclass exposed as context property that acts as the interface
between QML and C++. Of course, there are also other approaches
(qmlRegisterType(), etc..).

As far as the sailfish example application goes, this might be helpful:

http://blog.linux4us.org/2013/02/28/sailfishapplication-and-setcontextproperty/


HTH :)
Thomas
_______________________________________________
SailfishOS.org Devel mailing list

Reply via email to