QML call function in C++ with threads
-
I need a tip.
I have a class written in C ++ where I record it for use in my QML with qmlRegisterType, have functions where Q_INVOKABLE realize trough calls QML and sending some signals of C ++ data to QML.
But I want to improve it, and each function of my class I call via QML wanted to execute Thread and so all functions that call, how could it do?
Did not want to create threads in each role, I thought of something generic for calls or what would advise me?
I came to alumas ideas as:
https://wiki.qt.io/QThreads_general_usage -
If I am understanding your question it sounds to me that you want to register a singleton type and not a registered type so that it is only created once and you can call this
qmlRegisterSingletonType<MyClass>("MyImportName" ,1,0,"WhatIamCalledInQml", initSingleton)
where initSingleton would be the instance of the class that you are initializing
// Second, define the singleton type provider function (callback). static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) MyClass *myClass = new MyClass(); return myClass; }
So then in your Qml
import MyImportName 1.0 Item { ....... ................ ............................ Button { onClicked:{ WhatIamCalledInQml.process() } } Connections { taget: WhatIamCalledInQml onFinished : console.log ("Single Worker has finished " ) }
Of cource this is expecting that you have your Myclass wrapped up in a QThread kinda like the Worker example. But this could also happen in the init of the singleton. That is up to you.
From the example:
QThread* thread = new QThread; MyClass* myclass = new MyClass(); myclass->moveToThread(thread); // return the instance of the thread :)
-
@JosephMills said in QML call function in C++ with threads:
static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)MyClass *myClass = new MyClass(); return myClass;
}
This is not a singleton as you create a new instance each time this function is called. It should be:
static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) static MyClass *myClass = new MyClass(); return myClass; }
-
@jsulm said in QML call function in C++ with threads:
static
The class is only called when the import happens on the register side of qml/qtquick and the static function only gets called once on the registration.
qmlRegisterSingletonType<MyClass>("MyImportName" ,1,0,"WhatIamCalledInQml", initSingleton)
Here is a example.
use the code above to make the registered singleton
maybe even add a debug point at
// Second, define the singleton type provider function (callback). static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) qDebug() << "See only "; MyClass *myClass = new MyClass(); qDebug() << " once "; return myClass; }
say that MyClass had a invokable called printHi that just returned a QString of "Hello "
Then in QMLComponent.onCompleted: { for (var i = 0 ; i < 300; i++){ console.log(MyClass.printHi() + " And Index of loop = " +i) } }
You will see that "See only once" Is only printed one time during the life of the Application.
-
@JosephMills OK, understand. But the name singleton is somehow misleading.
-
@jsulm I hear that lol if you like take a look here
http://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonTypebecause it is the QObject that is getting returned from the template. Also would not hurt to make total static on the QObject,
-
I'll try to explain better what I need:
Here is an example code.
mytask.h and mytask.cpp
class myTask : public QObject
{
Q_OBJECTpublic:
myTask();virtual ~myTask(); Q_INVOKABLE void func1(void) { while(1) { qDebug() << "Running Func1" << endl; QThread::msleep(500); } } Q_INVOKABLE void func2(void) { while(1) { qDebug() << "Running Func2" << endl; QThread::msleep(500); } } Q_INVOKABLE void func3(void) { while(1) { qDebug() << "Running Func3" << endl; QThread::msleep(500); } }
}
main.cpp
...
// Register our component type with QML.
qmlRegisterType<myTask>("com.task", 1, 0, "MyTask");
...main.qml
...
MyTask {
id: task
}Rectangle { width: 50; height: width; color: "red" MouseArea { anchors.fill: parent onClicked: { console.log("call function 1 Qt/C++"); task.func1(); } } } Rectangle { width: 50; height: width; color: "blue" MouseArea { anchors.fill: parent onClicked: { console.log("call function 2 Qt/C++"); task.func2(); } } }
So I have to "fire" || "perform" functions (func1, func2, func3) as Threads and were running.
-
@jsulm said in QML call function in C++ with threads:
@JosephMills said in QML call function in C++ with threads:
static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)MyClass *myClass = new MyClass(); return myClass;
}
This is not a singleton as you create a new instance each time this function is called. It should be:
static QObject *initSingleton(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) static MyClass *myClass = new MyClass(); return myClass; }
It's a singleton with respect to the QML engine, not the process. Each engine will attempt to create its own singletons. Returning the same object to multiple engines might not achieve the desired result.
-
My idea is to call functions implemented in C ++ class but not "freeze" my application QML.
Calling directly without QThread, my QML freezes!
So I thought about using QtConcurrent or QThread for functions, I am evaluating.
-
@Cleiton-Bueno Are your C++ functions doing heavy calculations?
-
@jsulm said in QML call function in C++ with threads:
Are your C++ functions doing heavy calculations?
@jsulm No. A function will pooling and perform reading in a pin via SysFS, another function will "tick" on a pin, but are fired at different times and may be performed "together".
-
@Cleiton-Bueno Then I don't understand why your UI is freezing. Did you test and saw this freezing or do you just assume it will freeze?
-
@jsulm said in QML call function in C++ with threads:
Then I don't understand why your UI is freezing. Did you test and saw this freezing or do you just assume it will freeze?
@jsulm Because functions are with
while (true) {}
with 500ms delay, time is undetermined can be short or take a long time, and this function is sending a signal to my GUi QML that already ok. -
@Cleiton-Bueno Such loops are usually a sign of bad design. Especially in event based Qt you should avoid them. Why do you want to call a blocking function from QML? You should rethink your design and try to use signals/slots.
-
@jsulm This was an example!
I have no functions while (1), but have functions that when called will process for a while, for example, have a function that when activated will be communicating via I2C and the function returns me status of the Motor, until it stops.When I do that my QML GUI hangs as solve this with signals/slots? It would be helpful, used signals/slots but not in this case.
So I thought about using QThread within the function -
@Cleiton-Bueno If you don't want to block the UI you need asynchronous communication, even with a thread. That's why I suggested to use signals/slots. For example from the UI you could call a C++ function which triggers an action and returns immediately. As soon as the result is available your C++ code emits a signal with results which is connected to your UI.
If I understood you correctly you're already using a thread but your UI is still blocking, right? How do you use that thread? You should show some code. -
Sorry about the delay @jsulm.
I removed some parts of the code by NDA but I'm trying to expose the idea.mytask.h
#ifndef MYTASK_H #define MYTASK_H #include <QObject> #include <QTcpSocket> #include <QTimer> #include <QDebug> #include <QThread> class task : public QObject { Q_OBJECT Q_PROPERTY(QString msg READ msg WRITE setMsg NOTIFY msgChanged ) ... public: task(); virtual ~task(); Q_INVOKABLE void runGetMotor(void); ... QString err; private: QTcpSocket *socket; ... private slots: void onSocketReadData(); void onSocketConnected(); void onSocketDisconnected(); void onSocketError(QAbstractSocket::SocketError); signals: void progressMotor(int progress); ... }; #endif // MYTASK_H
mytask.cpp
//your code here #include "mytask.h" /** * @brief mytask::mytask * Metodo construtor e inicializaĆ§Ć£o de variaveis e objetos privados da classe task */ mytask::mytask() { if (DEBUG_TASK) qDebug() << "Init class and socket"; /* create socket */ socket = new QTcpSocket(this); if(DEBUG_TASK) qDebug() << "Connecting signal <-> slots"; connect(socket, SIGNAL(readyRead()), this, SLOT(onSocketReadData())); connect(socket, SIGNAL(connected()), this, SLOT(onSocketConnected())); connect(socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError))); } /** * @brief mytask::~mytask * Metodo destrutivo da classe mytask */ mytask::~mytask() { socket->close(); delete socket; } void mytask::runGoMotor(void) { ... this->runProgress(); ... } void mytask::runProgress(void) { /* Here I need to shoot this routine as Thread */ int returnLoop=255; while(returnLoop) { /* Here send/get command, process and emit signal send data to QML */ emit progressMotor(/* HERE VARIABLE WITH VALUE PROCESSED */); // Update value returnLoop or break loop QThread::sleep(1); } }
main.cpp
... // Register our component type with QML. qmlRegisterType<mytask>("com.sys.motor", 1, 0, "MyTask"); ...
main.qml
MyTask { id: task } Rectangle { ... onClicked: { task.runGoMotor(); } } Connections { target: task onProgressMotor: { console.log("Progress Motor: "+progress); //Set variable to show value } }
There are other checks and conditions to enter the while (), and at one point for the loop.
I'm auditioning QTimer starting in the constructor and it seems that met the need, something like:
MyTask::MyTask(QObject *parent) : QObject(parent) { timer = new QTimer(this); timer->setInterval(1000); connect(timer, SIGNAL(timeout()), this, SLOT(setProgressMotor())); }
The routine would be:
Click GUi QML button -> Function C ++ (runGoMotor ()), check some conditions and calls (runProgress ()), and in turn will send commands to the Socket and process the response, so to get something to close the loop.
-
@Cleiton-Bueno said in QML call function in C++ with threads:
while(returnLoop) {
/* Here send/get command, process and emit signal send data to QML /
emit progressMotor(/ HERE VARIABLE WITH VALUE PROCESSED */);
// Update value returnLoop or break loop
QThread::sleep(1);
}This while loop blocks the Qt event loop in your thread. That means: the signal will not be emitted until the loop is finished! You either should call http://doc.qt.io/qt-5/qcoreapplication.html#processEvents in the loop or, even better, get rid of this loop.
-
@jsulm said in QML call function in C++ with threads:
@Cleiton-Bueno said in QML call function in C++ with threads:
while(returnLoop) {
/* Here send/get command, process and emit signal send data to QML /
emit progressMotor(/ HERE VARIABLE WITH VALUE PROCESSED */);
// Update value returnLoop or break loop
QThread::sleep(1);
}This while loop blocks the Qt event loop in your thread. That means: the signal will not be emitted until the loop is finished!
Signals, which are a direct function call of moc-generated code, will be emitted. Events won't be processed in the thread, which means that queued connection slots in the same thread won't be called.
I agree that the forever { emit && sleep } construct is troubling.