首页 > 解决方案 > 如何使可见属性在 QML 中立即起作用?

问题描述

演示:

Window {
    visible: true
    width: 640
    height: 480

    Component.onCompleted: {
        test.visible = true // 1. Show rect
        for(var i = 0; i < 5000000000; i++){var t = i * i} // 2. Slow process, Sleep here
    }

    Rectangle {
        id: test
        color: "red"
        width: 100; height: 100
        visible: false
    }
}

功能完成时可见属性起作用。在演示中,test矩形无法显示1.,必须等到功能完成。

我知道这应该是由进程块渲染引起的。但是有什么技巧可以解决这个问题吗?

标签: qtqmlqt5

解决方案


繁重的任务不应在 GUI 线程中执行,而应在另一个线程中执行,以免它们被阻塞。QML 提供给 WorkerScript,这允许您在另一个线程中执行任务:

慢进程.js

WorkerScript.onMessage = function() {
    for(var i = 0; i < 5000000000; i++){
        var t = i * i
        console.log(t)
    }
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Component.onCompleted: {
        test.visible = true // 1. Show rect
        ws.sendMessage()
    }

    WorkerScript {
        id: ws
        source: "slow_process.js"
    }

    Rectangle {
        id: test
        color: "red"
        width: 100; height: 100
        visible: false
    }
}

推荐阅读