ubuntu-phone team mailing list archive
-
ubuntu-phone team
-
Mailing list archive
-
Message #21246
Re: connecting C++ to a QML button
On 17 June 2016 at 20:58, Matthias Apitz <guru@xxxxxxxxxxx> wrote:
>
> Hello,
>
> I'm trying to write my first QML/C++ app, so please be patient with me
> :-)
>
> The C++ main.cpp has:
>
> ...
> int main(int argc, char *argv[]) {
> QGuiApplication app(argc, argv);
> QQuickView v;
> QUrl file = (QUrl) "myRoot/home/phablet/baresip-app/baresip.qml";
>
> v.setSource(file);
> v.show();
>
> MyClass myClass;
>
> QObject *item = v.rootObject();
> QObject *newButton = item->findChild<QObject*>("dialButton");
> QObject::connect(newButton, SIGNAL(qmlSignal(QString)),
> &myClass, SLOT(cppSlot(QString)));
>
> return app.exec();
> }
>
> and the QML object is:
>
> import QtQuick 2.4
> import Ubuntu.Components 1.3
>
>
> MainView {
>
> Rectangle {
> id: page
> width: 540; height: 960
> color: "lightgray"
> border.color: "grey"
> border.width: 5
> radius: 10
>
> Text {
> id: baresipTitle
> ...
> }
>
> ...
>
> Item {
> id: dialButton
> x: 10
> y: 110
> property alias cellColor: rectangle.color
> property alias cellText: buttonText.text
>
> signal qmlSignal(string msg)
>
> width: 160; height: 50
>
> Rectangle {
> id: rectangle
> border.color: "blue"
> color: "lightgrey"
>
> anchors.fill: parent
>
> Text {
> id: buttonText
> text: "Dial"
> x: 8
> y: 24
> font.pointSize: 12
> }
> }
>
> MouseArea {
> anchors.fill: parent
> hoverEnabled: true
> onEntered: rectangle.border.color = "blue"
> onExited: rectangle.border.color = "green"
>
> onClicked: button.qmlSignal("Hello from QML")
> }
>
> cellColor: buttonMouseArea.pressed ? Qt.darker(buttonColor, 1.5) : buttonColor
> }
> ...
> }
>
> The app starts fine but the C++ part does not find the "dialButton", it
> says:
>
> Loading module: 'libubuntu_application_api_touch_mirclient.so.3.0.0'
> QObject::connect: Cannot connect (null)::qmlSignal(QString) to MyClass::cppSlot(QString)
>
> Sure, that I do something wrong, but what?
>
> Thanks for any help or pointer to help. The full project sources are
> attached.
When combining C++ and QML, it is usually easiest to connect
everything up from the QML side. You can register your class with QML
by adding the following statement on the C++ side:
qmlRegisterType<MyClass>("somemodule", 1, 0, "MyClass");
Now on the QML side, "import somemodule 1.0" will allow you to create
instances of MyClass. Any Q_PROPERTY declarations will be accessible
on the class, and any slots or methods marked with Q_INVOKABLE will be
callable from QML. Now you should be able to hook up the signal just
as you would for any other QML component.
James.
References