Signals and Slots in Qt QML
And we got to transfer data between a layer of QML and C ++ layer. Frankly speaking, the principle is as simple as just using signals and slots in a single layer C ++. Especially in Qt 5.5.
appcore.h β application core file header;
appcore.cpp β application core source file.
And we continue to work and be with QQMLApplicationEngine. You will need to just take from the engine QML context and download it to a new class of object from which the signals in which data will be transmitted will be received.
appcore.h
Our class header file is as simple as a penny. In it there is a one meter (variable of type int), a slot that will increase the counter by one and run signal, which is also one in the class and which will transmit the counter value in QML-interface.
#ifndef APPCORE\_H
#define APPCORE\_H
#include <QObject>
class AppCore : public QObject
{
Q\_OBJECT
public:
explicit AppCore(QObject *parent = 0);
signals:
// Signal to transmit data to interface qml-interface
void sendToQml(int count);
public slots:
// The slot for the receiving of data from the QML-interface
void receiveFromQml();
private:
int count; // Counter
};
#endif // APPCORE\_Happcore.cpp
main.cpp
And here we have connected to our class interface written in QML.
main.qml
Here is part of the code, so as not to distract you from the main. Namely, a compound layer in QML Connections by means of the object as a target is set your class is indicated in the context. Treatment is carried out on the text name that is loaded into the QML engine context, together with the object itself.
To receive signals from the C ++ layer is necessary in the Connections register a function that will be called in much the same way as the target signal, but will start on a signal and then the name with a capital letter. That is, the following logic
signalToQml β on C++
onSignalToQml β on QML
But the call Slot will be somewhat different. For example, we have a class object in C ++, to which we refer by name appCore (declared aim in Connections). And then we call the slot. That is as follows: appCore.slotSomething (count).
Call slot in this code is done by pressing the OK button in the dialog, and in Cancel the call does not occur. At the same time, appCore object in C ++ code, the counter increases by one and causes the signal to put counter value in a text label applications.
Result
The result is a simple interaction between the C ++ and QML based on all of the same signals and slots. But the result of the application you can see in the video tutorial.
Last updated
Was this helpful?