临沂手机网站信息推广技术公司电话,惠州网络问政平台官网,seo怎么优化排名,新网站做内链1. 实现功能
QML项目中#xff0c;点击一个按键后#xff0c;运行一段比较耗时的程序#xff0c;此时ui线程会卡住。如何避免ui线程卡住。
2. 单线程#xff08;会卡住#xff09;
2.1 界面 2.2 现象
点击delay btn后#xff0c;执行耗时函数#xff08;TestJs.func…1. 实现功能
QML项目中点击一个按键后运行一段比较耗时的程序此时ui线程会卡住。如何避免ui线程卡住。
2. 单线程会卡住
2.1 界面 2.2 现象
点击delay btn后执行耗时函数TestJs.func_delay()界面阻塞阻塞了12s等待运行完成后点击ui btn才能响应。
qml: 2024-11-14 09:48:29 ui thread
qml: 2024-11-14 09:48:30 click delay btn
qml: delay thread 2024-11-14 09:48:42
qml: 2024-11-14 09:48:42 ui thread2.3 main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import test.js as TestJsWindow {width: 640height: 480visible: truetitle: qsTr(Thread)Row{spacing: 20Button{width: 200height: 100text: ui btnonClicked: {console.log(Qt.formatDateTime(new Date(), yyyy-MM-dd HH:mm:ss), ui thread)}}Button{width: 200height: 100text: delay btnonClicked: {console.log(Qt.formatDateTime(new Date(), yyyy-MM-dd HH:mm:ss), click delay btn)TestJs.func_delay()}}}
}
2.4 test.js //耗时函数
function func_delay() {var cnt 0;for(let i0; i1000000000; i){cnt;}console.log(delay thread, Qt.formatDateTime(new Date(),yyyy-MM-dd HH:mm:ss))
}
3. 多线程WorkerScript方式
3.1 界面 3.2 现象
将耗时函数(func_delay())放到WorkerScript.onMessage中执行这样ui线程不会阻塞。ui线程与delay线程直接可以通讯发送通过sendMessage接收通过onMessage
qml: 2024-11-14 09:54:11 ui thread
qml: 2024-11-14 09:54:11 click delay btn-1
qml: 2024-11-14 09:54:11 click delay btn-2
qml: 2024-11-14 09:54:12 ui thread
qml: 2024-11-14 09:54:13 ui thread
js: delay thread 2024-11-14 09:54:23
js: ui thread - delay thread: Hello, I am ui thread.
qml: delay thread - ui thread: Hello, I am delay thread.3.3 main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import test.js as TestJsWindow {width: 640height: 480visible: truetitle: qsTr(Thread)Row{spacing: 20Button{width: 200height: 100text: ui btnonClicked: {console.log(Qt.formatDateTime(new Date(), yyyy-MM-dd HH:mm:ss), ui thread)}}Button{width: 200height: 100text: delay btnonClicked: {console.log(Qt.formatDateTime(new Date(), yyyy-MM-dd HH:mm:ss), click delay btn-1)//发送数据myWorker.sendMessage({msg: Hello, I am ui thread.})console.log(Qt.formatDateTime(new Date(), yyyy-MM-dd HH:mm:ss), click delay btn-2)}}WorkerScript{id: myWorkersource: test.js//接收数据onMessage: {console.log(delay thread - ui thread: , messageObject.msg)}}}
}
3.4 test.js function func_delay() {var cnt 0;for(let i0; i1000000000; i){cnt;}console.log(delay thread, Qt.formatDateTime(new Date(),yyyy-MM-dd HH:mm:ss))
}WorkerScript.onMessage function(message){func_delay()console.log(ui thread - delay thread: , message.msg)//发送数据WorkerScript.sendMessage({msg: Hello, I am delay thread.})
}
参考
Qt 之 qml WorkerScript使用