申請(qǐng)免費(fèi)網(wǎng)站建設(shè)seo排名優(yōu)化
1. 實(shí)現(xiàn)功能
QML
項(xiàng)目中,點(diǎn)擊一個(gè)按鍵后,運(yùn)行一段比較耗時(shí)的程序,此時(shí)ui線程
會(huì)卡住。如何避免ui線程
卡住。
2. 單線程(會(huì)卡住)
2.1 界面
2.2 現(xiàn)象
- 點(diǎn)擊
delay btn
后,執(zhí)行耗時(shí)函數(shù)(TestJs.func_delay()
)界面阻塞(阻塞了12s
),等待運(yùn)行完成后,點(diǎn)擊ui btn
才能響應(yīng)。
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 thread
2.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 btn"onClicked: {console.log(Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"), "ui thread")}}Button{width: 200height: 100text: "delay btn"onClicked: {console.log(Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"), "click delay btn")TestJs.func_delay()}}}
}
2.4 test.js
//耗時(shí)函數(shù)
function func_delay() {var cnt = 0;for(let i=0; i<1000000000; i++){cnt++;}console.log("delay thread", Qt.formatDateTime(new Date(),"yyyy-MM-dd HH:mm:ss"))
}
3. 多線程(WorkerScript
方式)
3.1 界面
3.2 現(xiàn)象
- 將耗時(shí)函數(shù)(
func_delay()
)放到WorkerScript.onMessage
中執(zhí)行,這樣ui線程不會(huì)阻塞。 - ui線程與delay線程直接可以通訊,發(fā)送通過(guò)
sendMessage
,接收通過(guò)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 btn"onClicked: {console.log(Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"), "ui thread")}}Button{width: 200height: 100text: "delay btn"onClicked: {console.log(Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"), "click delay btn-1")//發(fā)送數(shù)據(jù)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"//接收數(shù)據(jù)onMessage: {console.log("delay thread -> ui thread: ", messageObject.msg)}}}
}
3.4 test.js
function func_delay() {var cnt = 0;for(let i=0; i<1000000000; 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)//發(fā)送數(shù)據(jù)WorkerScript.sendMessage({'msg': 'Hello, I am delay thread.'})
}
參考
Qt 之 qml WorkerScript使用