-
Notifications
You must be signed in to change notification settings - Fork 2
/
qttimerjs_plugin.cpp
63 lines (49 loc) · 1.63 KB
/
qttimerjs_plugin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "qttimerjs_plugin.hpp"
#include <qqml.h>
QtTimerJSPlugin::QtTimerJSPlugin() : timerjs(new TimerJS(this)) {}
void QtTimerJSPlugin::initializeEngine(QQmlEngine *engine, const char *) {
engine->rootContext()->setContextObject(timerjs);
}
void QtTimerJSPlugin::registerTypes(const char *uri) {
Q_ASSERT(uri == QLatin1String("QtTimerJS"));
qmlRegisterModule(uri, 1, 0);
}
QVariant TimerJS::setTimeout(const QVariant &handler, int time,
bool singleShot) const {
auto value = handler.value<QJSValue>();
if (!value.isCallable()) {
qWarning() << "handler is not a value callable";
return {QJSValue::SpecialValue::UndefinedValue};
}
QTimer *timer = new QTimer();
timer->setSingleShot(singleShot);
timer->callOnTimeout([value]() mutable { value.call(); });
Lambda disconnect([timer]() mutable {
if (timer) {
if (timer->isActive()) {
QMetaObject::invokeMethod(timer, "stop", Qt::QueuedConnection);
}
timer->deleteLater();
timer = nullptr;
}
});
if (singleShot)
timer->callOnTimeout(disconnect);
timer->start(time);
return QVariant::fromValue(disconnect);
}
QVariant TimerJS::setTimeout(const QVariant &handler, int time) const {
return setTimeout(handler, time, true);
}
void TimerJS::clearTimeout(const QVariant &handler) const {
if (handler.canConvert<Lambda>()) {
auto disconnect = handler.value<Lambda>();
disconnect();
}
}
QVariant TimerJS::setInterval(const QVariant &handler, int time) const {
return setTimeout(handler, time, false);
}
void TimerJS::clearInterval(const QVariant &handler) const {
clearTimeout(handler);
}