Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTimer::singleShot equivalent for QML

Tags:

qt

qml

Consider this C++ statement (example from docs):

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

How to do the same in .qml JavaScript, something like this QML:

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

There's the obvious solution of having separate Timer, which is then started by this JavaScript code, and I'll accept that as an answer if a one-liner is not possible. Is it?

like image 606
hyde Avatar asked Jun 10 '15 11:06

hyde


People also ask

What is QTimer singleShot?

[static] void QTimer::singleShot(int msec, const QObject *receiver, const char *member) This static function calls a slot after a given time interval. It is very convenient to use this function because you do not need to bother with a timerEvent or create a local QTimer object.

What is QTimer?

The QTimer class provides repetitive and single-shot timers. The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on it will emit the timeout() signal at constant intervals.

How do I restart QTimer?

To stop call QTimer::stop . To restart just call QTimer::start .


2 Answers

I ended up adding this to my 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();
}

Which can be used like this:

delayCall( 1000, function () { ... } );
like image 166
Ivan Kolev Avatar answered Sep 27 '22 19:09

Ivan Kolev


Change "repeat" property to false for Timer object.

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
            }
        }
    }
}
like image 40
synacker Avatar answered Sep 27 '22 19:09

synacker