Connections介绍: https://doc.qt.io/qt-5/qml-qtqml-connections.html
示例:倒计时
worker.h
#ifndef DISPATCHER_H
#define DISPATCHER_H
#include <QThread>
#include <QDebug>
class Worker : public QThread
{
Q_OBJECT
Q_PROPERTY(int data READ getData WRITE setData NOTIFY dataChanged )
public:
explicit Worker() = default;
~Worker() = default;
void run() {
qDebug() << "Inside the worker thread!";
for ( int i = 10; i >= 0; --i ) {
setData(i);
sleep( 1 );
}
}
Q_INVOKABLE int getData() const { return data_; }
// TODO: add signals for each type of received message by the worker thread?
signals:
void dataChanged( const int data );
public slots:
void setData( const int data ) {
if ( data != data_ ) {
data_ = data;
emit dataChanged( data_ );
}
}
private:
int data_ = 0 ;
};
#endif // DISPATCHER_H
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QThread>
#include <QQmlEngine>
#include <QQmlContext>
#include "worker.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
Worker worker;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("theworker", &worker);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
id: root
visible: true
width: 640
height: 480
title: qsTr("线程")
Rectangle {
color: "orange"
anchors.fill: parent
objectName: "test"
Text {
id: thetext
text: "倒计时"
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
textFormat: Text.AutoText
fontSizeMode: Text.FixedSize
font.pointSize: 40
anchors.horizontalCenter: parent.horizontalCenter
anchors.fill: parent
Button {
id: startbutton
x: 503
y: 406
text: qsTr("开始")
onClicked: {
theworker.start() // 开启线程
}
}
}
}
Connections { //连接的目标不在QML中
target: theworker //指向发出信号的对象
onStarted: {
print('线程开启')
}
onDataChanged: {
print('计时改变: ' + theworker.getData() );
thetext.text = theworker.getData();
}
}
Component.onDestruction: theworker.terminate();
}