This article was first published on my blog huanghaozi. Cn, original link
The introduction
Qt is known for its ease of developing cross-platform applications, and QML is comfortable to look at. However, this time I wanted to implement a similar function like hold and hold, but I did not find the related function in the API (one of the onPressedAndHold functions cannot be implemented), if the onPressedChange is installed in the dead loop, the state of the button will not change during the execution, the process will be stuck in the dead loop. After a lot of searching, I finally chose to dock with the QML implementation in C++.
multithreading
Implementing multithreading in qt C++ is very easy. You just need to write a class that inherits QThread (which is just one of the methods) and plug the thread starting code into a private run function (the run function can’t take arguments, you can put them in class objects). Thread needs to accept a parameter to determine the hold state, so I add a bool pointer to public to separate the implementation from the declaration as.h and.cpp, as follows:
/****worker.h****/
#pragma once
#include <QtCore>
#ifndef WORKER_H
#define WORKER_H
class Worker : public QThread
{
public:
bool* holding; // Determine whether to hold down
private:
void run(a); // execute when the thread starts
};
#endif
/****worker.cpp****/
#include "worker.h"
void Worker::run()
{
int i = 0;
while(* (this->holding)) { // The loop condition is holding variable true
qDebug()<<"holding for "<<i<<" seconds.";
QThread::msleep(1000); // Output every second while holding downi++; }}Copy the code
C++ interconnects with QML
To connect c++ to QML, we also need to make a class that inherits from QObject. Besides connecting it to QML, we also need to connect it to thread class, so I give it a thread class pointer
/****qccon.h****/
#pragma once
#include "worker.h"
#ifndef QCCON_H
#define QCCON_H
class QcCon : public QObject
{
Q_OBJECT
public:
Worker* w; // Thread docking pointer
//QCoreApplication* a;
Q_INVOKABLE void toCpp(const QString &); // QML callable function
};
#endif
/****qccon.cpp****/
#include "qccon.h"
void QcCon::toCpp(const QString &msg) // QML callable function
{
if(msg == "t") // If the message from QML is t, the thread holding variable is set to true
{
*(w->holding) = true;
w->start(); // Open the thread
}
else
*(w->holding) = false;
//QObject::connect(w, SIGNAL(finished()), a, SLOT(quit()));
}
Copy the code
The main function
The main function creates instances of these two classes and binds them to QML using the following code:
#include "qccon.h".// add to main
QcCon m;
Worker w;
m.w = &w;
engine.rootContext()->setContextProperty("qccon", &m);
// add m to QML and the corresponding QML is named qccon
Copy the code
In QML, you can call qccon directly to pass information to c++, as follows
onPressedChanged: {
if(this.pressed)
qccon.cppMethod("t");
else
qccon.cppMethod("f");
}
Copy the code
This article was automatically published by ArtiPub