QTimer :: singleShot等效于QML

时间:2015-06-10 11:03:29

标签: qt qml

考虑这个C ++语句(例如from docs):

QTimer::singleShot(600000, &app, SLOT(quit()));

如何在.qml JavaScript中执行相同的操作,如此QML:

Rectangle {
    property int counter: 0
    onCounterChanged: {
        if (counter > 42) {
            // do equivalent of above C++ statement here
        }
    }
    // more code, which actually manipulates counter 
}

有明显的解决方案是单独Timer,然后由此JavaScript代码启动,如果不能使用单行代码,我会接受这个答案。是吗?

4 个答案:

答案 0 :(得分:9)

将Timer对象的“repeat”属性更改为false。

import QtQuick 1.0

Item {
    Timer {
        id: timer
        interval: 600000
        running: false
        repeat: false
        onTriggered: Qt.quit()
    }

    Rectangle {
        property int counter: 0
        onCounterChanged: {
            if (counter > 42) {
                timer.running = true
            }
        }
    }
}

答案 1 :(得分:8)

我最后将它添加到我的main.qml:

Component {
    id: delayCallerComponent
    Timer {
    }
}

function delayCall( interval, callback ) {
    var delayCaller = delayCallerComponent.createObject( null, { "interval": interval } );
    delayCaller.triggered.connect( function () {
        callback();
        delayCaller.destroy();
    } );
    delayCaller.start();
}

可以这样使用:

delayCall( 1000, function () { ... } );

答案 2 :(得分:1)

以下是使用SequentialAnimation元素的方法:

SequentialAnimation {
    id: quitTimer
    PauseAnimation { duration: 60000 }
    ScriptAction { script: Qt.quit() }
}

Rectangle {
    property int counter: 0
    onCounterChanged: {
        if (counter > 42) {
            quitTimer.start()
        }
    }
}

如果太丑陋,则用它制成一个组件:

// SingleshotTimer.qml
import QtQuick 2.0
SequentialAnimation {
    property alias delay: delayAnim.duration
    property alias action: scriptAction.script

    PauseAnimation { id: delayAnim; duration: 10000 }
    ScriptAction { id: scriptAction }
}

使用此新组件将提供您想要的:

SingleshotTimer { id: timer; delay: 60000; action: Qt.quit() }

Rectangle {
    property int counter: 0
    onCounterChanged: {
        if (counter > 42) {
            timer.start()
        }
    }
} 

答案 3 :(得分:0)

QML中有一个计时器组件

predictions
    1 
18675

了解更多详情,see the documentation