QtQuick and C++ or QML + Javascript ?
-
Hello,
i have a simple application with fields and buttons. I want to use QtQuick to build this application (originally written for desktop, but i might have a need for mobile version in the future)
The purpose is to query the user for some information (specs of optic devices) and then the app computes and displays the results.
Here are my multiple questions :
-
i designed a qml view with buttons and fields. I feel the right way to go would be to grab the entered values and compute them using c++ and then re-publishing the results to the qml view to display them ? Here i am lost among the different solutions that exists to share variables between qml and c++... which one would you recommend (and how !). Note i will have something like 10 variables to share.
-
As i understand, simple behaviors and computations can be managed directly into QML using Javascript ? What would be the bet way then, QtQuick and C++ or QML + Javascript ?
thanks a lot
-
-
Hello,
Personally, I would rather use QML and C++ than QML and JavaScript, because I originally am a C++ developper than a Web Developper.But, I guess the better way is use JavaScript for functions will not be often called and not very complexe, and C++ for heavy functions or others.
To do that, I guess we should do something like that:
- Create component in C++ by inherated from QObject. It could be an inheritance from QAbstractItemModel and register them to QML
- Create all the GUI application in QML and use components created in C++.
But it is only my opinion ^^.
-
Hello,
Personally, I would rather use QML and C++ than QML and JavaScript, because I originally am a C++ developper than a Web Developper.But, I guess the better way is use JavaScript for functions will not be often called and not very complexe, and C++ for heavy functions or others.
To do that, I guess we should do something like that:
- Create component in C++ by inherated from QObject. It could be an inheritance from QAbstractItemModel and register them to QML
- Create all the GUI application in QML and use components created in C++.
But it is only my opinion ^^.
Hello !
Thank you for your suggestions.
I am quite a noob in QML and i am a bit confused though
@qnope said:
To do that, I guess we should do something like that:
- Create component in C++ by inherated from QObject. It could be an inheritance from QAbstractItemModel and register them to QML
- Create all the GUI application in QML and use components created in C++.
How would you do that !?
Thanks a lot.
-
Hello ^^.
I am not very convenient is QML as well.
But,- Create component in C++ is easy : http://doc.qt.io/qt-5/qtqml-referenceexamples-adding-example.html
- I made a little example using thread and use also QML and c++ here : https://forum.qt.io/topic/62073/qthread-qml
Maybe it could help you :).
-
hello,
thanks for your answer.
I tried to bind c++ variables to QML using qmlRegisterType. I created a class Worker and declared a Q_PROPERTY (which seems to build) but i still don't understand how to access them from qml : when i use Worker in qml, it only shows me the access to the private variable but none of the public methods or slots.
I don't understand the logic behind all of this.
Maybe i should stick to QtWidgets for the moment.
-
No.
I thought Q_PROPERTY was the way to go but i can't make it to work.
In fact, the problem is that even after reading the documentation on how to bind data between C++ and QML i don't get the logic behind the scene and i don't understand the specifics of each solutions (there seem to have several) and their purpose...
well, i can understand C++ and QML separately, but i don't get the link between them...
I also had a look to the "texteditor" example project which uses QML along with a C++ class. I can access certain methods from QML but i can't see any Q_INVOKABLE macro.
I must be missing something
main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include "worker.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); //Register custom C++ class to use with QML qmlRegisterType<Worker>("Worker.Interface", 1,0, "Worker"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }Worker.h
#ifndef WORKER_H #define WORKER_H #include <QObject> class Worker : public QObject { Q_OBJECT Q_PROPERTY(bool bSurface READ surface WRITE setSurface) public: explicit Worker(QObject *parent = 0); bool surface(); void setSurface(bool value); signals: public slots: private: bool bSurface; }; #endif // WORKER_HWorker.cpp
#include "worker.h" Worker::Worker(QObject *parent) : QObject(parent) { } bool Worker::surface() { return bSurface; } void Worker::setSurface(bool value) { bSurface = value; }main.qml
import QtQuick 2.3 import QtQuick.Controls 1.2 import Worker.Interface 1.0 ApplicationWindow { visible: true width: 292 height: 404 title: qsTr("Mapping Abak") menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("&Open") onTriggered: console.log("Open action triggered"); } MenuItem { text: qsTr("Exit") onTriggered: Qt.quit(); } } } TextField { id: pixelWidth x: 10 y: 77 text: "" readOnly: false placeholderText: qsTr("largeur") } TextField { id: pixelHeight x: 180 y: 77 text: "" readOnly: false placeholderText: qsTr("hauteur") } GroupBox { id: groupFormat x: 10 y: 11 width: 270 height: 55 title: qsTr("FORMAT") Text { id: x x: 130 y: 79 width: 30 height: 18 text: qsTr("X") horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter font.pixelSize: 12 } ExclusiveGroup { id: calcGroup } Button { id: buttonSurface x: 10 y: 110 text: qsTr("Surface") checked: false checkable: true exclusiveGroup: calcGroup // this won't work //onCheckedChanged: Worker.setSurface(true) } TextField { id: imageWidth x: 10 y: 229 readOnly: false placeholderText: qsTr("") //enabled : if (buttonSurface.checked) {false} else {true} } } -
Hello,
Thanks to Q_INVOKABLE, you are able to call a function from C++.You can have example on the link I posted before (QML, QThreads), http://doc.qt.io/qt-5/qobject.html#Q_INVOKABLE (Qt Doc) and http://stackoverflow.com/questions/9341005/connecting-c-with-qml-using-q-invokable (Stack Overflow).
-
No.
I thought Q_PROPERTY was the way to go but i can't make it to work.
In fact, the problem is that even after reading the documentation on how to bind data between C++ and QML i don't get the logic behind the scene and i don't understand the specifics of each solutions (there seem to have several) and their purpose...
well, i can understand C++ and QML separately, but i don't get the link between them...
I also had a look to the "texteditor" example project which uses QML along with a C++ class. I can access certain methods from QML but i can't see any Q_INVOKABLE macro.
I must be missing something
main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include "worker.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); //Register custom C++ class to use with QML qmlRegisterType<Worker>("Worker.Interface", 1,0, "Worker"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }Worker.h
#ifndef WORKER_H #define WORKER_H #include <QObject> class Worker : public QObject { Q_OBJECT Q_PROPERTY(bool bSurface READ surface WRITE setSurface) public: explicit Worker(QObject *parent = 0); bool surface(); void setSurface(bool value); signals: public slots: private: bool bSurface; }; #endif // WORKER_HWorker.cpp
#include "worker.h" Worker::Worker(QObject *parent) : QObject(parent) { } bool Worker::surface() { return bSurface; } void Worker::setSurface(bool value) { bSurface = value; }main.qml
import QtQuick 2.3 import QtQuick.Controls 1.2 import Worker.Interface 1.0 ApplicationWindow { visible: true width: 292 height: 404 title: qsTr("Mapping Abak") menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("&Open") onTriggered: console.log("Open action triggered"); } MenuItem { text: qsTr("Exit") onTriggered: Qt.quit(); } } } TextField { id: pixelWidth x: 10 y: 77 text: "" readOnly: false placeholderText: qsTr("largeur") } TextField { id: pixelHeight x: 180 y: 77 text: "" readOnly: false placeholderText: qsTr("hauteur") } GroupBox { id: groupFormat x: 10 y: 11 width: 270 height: 55 title: qsTr("FORMAT") Text { id: x x: 130 y: 79 width: 30 height: 18 text: qsTr("X") horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter font.pixelSize: 12 } ExclusiveGroup { id: calcGroup } Button { id: buttonSurface x: 10 y: 110 text: qsTr("Surface") checked: false checkable: true exclusiveGroup: calcGroup // this won't work //onCheckedChanged: Worker.setSurface(true) } TextField { id: imageWidth x: 10 y: 229 readOnly: false placeholderText: qsTr("") //enabled : if (buttonSurface.checked) {false} else {true} } }@Marty said:
I thought Q_PROPERTY was the way to go but i can't make it to work.
In fact, the problem is that even after reading the documentation on how to bind data between C++ and QML i don't get the logic behind the scene and i don't understand the specifics of each solutions (there seem to have several) and their purpose...
Properties expose a variable to QML that can have C++ defined behavior. Eg the property getter can return a value based on a calculation rather than directly passing a value stored in a C++ variable. A setter can validate the requested value before accepting or rejecting it. Acceptance of the passed value, or the use of another value is indicated by emitting the NOTIFY signal. Properties can inform a QML UI that the value has changed, perhaps due to external, asynchronous mechanisms. Properties can be on the left or right side of a binding.
Q_INVOKABLE defines a function that can be called from QML/Javascript. The function can have parameters and return a value, but it can not indicate an asynchronous change. Q_INVOKABLES can only be on the right side of a binding.
Class Type: public QObject { Q_PROPERTY(bool myProp READ getMyProp WRITE setMyProp NOTIFY myPropChanged) bool prop; Q_INVOKABLE int getValue() { return 14; } bool getMyProp() { return prop; } void setMyProp (bool value) { if (value != prop) { prop = value; emit myPropChanged(prop); } // else - ignore the requested change } };Type { id: instanceOfType myProp: true } property bool copy: instanceOfType.myProp property int value: instanceOfType.getValue()Worker.h
[...]
Q_PROPERTY(bool bSurface READ surface WRITE setSurface)
[...]bSurface is missing a NOTIFY signal. Without this, bindings using the property won't notice when the property's value changes. The documentation says that NOTIFY is optional, but all QML-facing properties should have either NOTIFY or CONSTANT. There's probably a warning emitted at runtime mentioning this.
http://doc.qt.io/qt-5/properties.html
main.qml
[...] // this won't work //onCheckedChanged: Worker.setSurface(true)There are several issues here. Worker is registered as a regular type, not a singleton. The QML engine needs an instance of Worker to interact with.
Worker::setSurface() is not Q_INVOKABLE. The property system knows about the function, but QML doesn't know how to invoke it directly.
-
Thanks a lot for the great explanation @jeremy_k !
You cast some light on several points, really usefulNow what i understand is when you do something like
Q_PROPERTY(int pixelWidth READ pixelWidth WRITE setPixelWidth NOTIFY pixelWidthChanged)then using it in QML
text: Worker.pixelWidth // this is calling the getter function onClicked: Worker.pixelWidth = 1920 // this is calling the setter functionWhich is not obvious when you start using C++ bindings on QML
I then use Q_INVOKABLE to trig some functions to do some process or calculations.
One thing i still don't get : i can't use any C++ signal in QML
I thought when using NOTIFY keyword in Q_PROPERTY i could then use it in my QML likeonPixelWidthChanged: // make somethingwhich is not the case
You can find the updated code here : https://gist.github.com/martialgallorini/66a486aea1f4ce884dc4
thanks a lot
-
Thanks a lot for the great explanation @jeremy_k !
You cast some light on several points, really usefulNow what i understand is when you do something like
Q_PROPERTY(int pixelWidth READ pixelWidth WRITE setPixelWidth NOTIFY pixelWidthChanged)then using it in QML
text: Worker.pixelWidth // this is calling the getter function onClicked: Worker.pixelWidth = 1920 // this is calling the setter functionWhich is not obvious when you start using C++ bindings on QML
I then use Q_INVOKABLE to trig some functions to do some process or calculations.
One thing i still don't get : i can't use any C++ signal in QML
I thought when using NOTIFY keyword in Q_PROPERTY i could then use it in my QML likeonPixelWidthChanged: // make somethingwhich is not the case
You can find the updated code here : https://gist.github.com/martialgallorini/66a486aea1f4ce884dc4
thanks a lot
It looks like the Worker code is missing an explicit emission of the pixelWidthChanged signal.
void Worker::setPixelWidth(int value) { if (value != _pixelWidth) { // don't report unnecessary changes _pixelWidth = value; emit pixelWidthChanged(); // this enables: - reevaluation of existing bindings to pixelWidth // - onPixelWidthChanged signal handlers } }The guard for the value change is useful because it prevents extra work by the QML engine. Each emission of a change signal causes the corresponding READ function to be called, which may lead to needless reevaluation of bindings.
For properties declared in QML, the engine handles sending signals and filtering no-op writes. In C++, the developer has more control but also more responsibility.
-
I tried to emit the signal within the Worker::setPixelWidth() function
I tried again following your suggestion but still no luck
-
Bit of a topic jump, but if I understand correctly, the current issue is that Creator isn't offering autocompletion for the onPixelWidthChanged signal handler.
From the screenshot, it looks like the handler is being defined in a TextField, not a Worker. That doesn't work because Creator and the QML engine look for a matching signal from the scope of the object containing the handler. Two easy options for handling a signal from another object are:
Connections QML type:
Worker { id: worker } TextField { id: textfield } Connections { target: worker onPixelWidthChanged: textfield.text = "signal handled" }Propagate from the source object:
Worker { onPixelWidthChanged: textfield.text = "signal handled" } TextField { id: textfield } -
Ok. This makes sense... but nope !
The simple goal here is :
- i have multiple choices (video format) : radio buttons
- i have two textfields : one for the width and one for the height of the image in pixels
- if selected video format is 16/9 : if i change the image width, the height is automatically calculated. I i change the height, the width is calculated.
All this made me learn a lot about QML but i still miss something.
I can't even make a textfield display a value according to what is entered in another textfield...
-
Is the question at this point how to get one text input to depend on another and the reverse (without a binding loop)?
This demonstrates two text inputs, top and bottom. Type into top, click on bottom, and the text in bottom is changed. There are other mechanisms for deciding when to update the non-selected text input. onEditingFinished happens to make for a simple if imperfect example.
import QtQuick 2.3 import QtQuick.Window 2.2 Window { visible: true TextInput { id: top width: parent.width height: parent.height / 2 - 1 onEditingFinished: bottom.text = "from top: " + text } Rectangle { height: 1 width: parent.width anchors.centerIn: parent color: "black" } TextInput { id: bottom width: parent.width height: parent.height / 2 - 1 anchors.bottom: parent.bottom onEditingFinished: top.text = "from bottom: " + text } } -
hello,
yes this works. It already did that way. But where i can't get it to work is when using c++ bindings
https://gist.github.com/martialgallorini/66a486aea1f4ce884dc4
-
Once the basic mechanisms of type registration and get/set/notify functions for a property are working, Qml versus C++ should not matter.
Have you tried producing a smaller example, eliminating everything unrelated to the issue? The process may make the issue obvious to you. It would certainly help me. I'm guessing that your expectation is that this line will result in param.pixelHeight being updated:
main.qml line 41: onEditingFinished: param.calcPixelHeight()What I'm missing is an attempt to change the value of param.pixelWidth. Editing the pixelWidth TextField will result in param.pixelHeight be recalculated with the default param.pixelWidth, not the content of the TextField.
-
As a general rule, please post code examples to the forum, or at least to somewhere unlikely to change or disappear. It helps keep threads useful for future readers.
The Worker pixelWidth property is uninitialized and the UI doesn't provide a way to set it. Triggering the pWidth onEditingFinished handler has undefined behavior in the process of updating pixelHeight. Presumably the goal is to have the TextInputs display pixelWidth and pixelHeight, in which case the text properties of each input should be bound to the respective worker properties. Changing the worker properties can be achieved by setting them using onEditingFinished instead of or prior to calling Worker::calcHeight()
-
Hello,
Yes i know, but i find the code presentation on this forum very messy and difficult to read...
Here what i have so far, which is working :
Worker.h
#ifndef WORKER_H #define WORKER_H #include <QObject> class Worker : public QObject { Q_OBJECT Q_PROPERTY(float pixelWidth READ pixelWidth WRITE setPixelWidth NOTIFY pixelWidthChanged) Q_PROPERTY(float pixelHeight READ pixelHeight WRITE setPixelHeight NOTIFY pixelHeightChanged) public: explicit Worker(QObject *parent = 0); float pixelWidth(); void setPixelWidth(float value); float pixelHeight(); void setPixelHeight(float value); Q_INVOKABLE void calcHeight(); signals: void pixelWidthChanged(); void pixelHeightChanged(); public slots: private: float _pixelHeight; float _pixelWidth; }; #endif // WORKER_HWorker.cpp
#include "worker.h" Worker::Worker(QObject *parent) : QObject(parent) { //_pixelWidth = 1920; } float Worker::pixelWidth() { return _pixelWidth; } void Worker::setPixelWidth(float value) { _pixelWidth = value; emit pixelWidthChanged(); } float Worker::pixelHeight() { return _pixelHeight; } void Worker::setPixelHeight(float value) { _pixelHeight = value; emit pixelHeightChanged(); } void Worker::calcHeight() { _pixelHeight = (_pixelWidth * 9) / 16; emit pixelHeightChanged(); }main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include "worker.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterType<Worker>("Worker.interface", 1, 0, "Worker"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }main.qml
import QtQuick 2.3 import QtQuick.Controls 1.2 import Worker.interface 1.0 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Worker { id: worker } menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("&Open") onTriggered: console.log("Open action triggered"); } MenuItem { text: qsTr("Exit") onTriggered: Qt.quit(); } } } TextInput { id: pWidth x: 210 y: 118 width: 230 height: 43 text: worker.pixelWidth font.pixelSize: 21 onEditingFinished: { worker.pixelWidth = text worker.calcHeight() } } TextInput { id: pHeight x: 210 y: 193 width: 230 height: 47 text: worker.pixelHeight font.pixelSize: 21 } }thanks a lot for your support