From f1f610bc67bfd5c2ef31270a6945e7bae93b5e4a Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Thu, 19 Dec 2024 14:10:31 +0200 Subject: Qt Timers: disallow setting negative intervals As disccussed in the code review. Replace negative values with 1ms (not 0ms as that would spin up the event-loop too many times). Move QTimer::start(std::chrono::milliseconds msec) API docs next to the method definition so as to not forget changing it when the implementation changes. Drive-by, qWarning() and co. are marked cold so there is no need to use Q_UNLIKELY in an if-condition leading to calling these methods. [ChangeLog][QtCore][Important Behvaior Change] Timers with negative intervals aren't allowed anymore, that is, if you try to start a timer (or set the interval) with a negative value, that interval will be set to 1ms. Previously Qt timers would let you set the interval to a negative value, but behave in surprising ways (for example stop the timer if it was running or not start it at all). This change affects QTimer, QChronoTimer, QBasicTimer and QObject::startTimer(). Fixes: QTBUG-132359 Change-Id: I09309063665db051337f91160971993d9ce7911e Reviewed-by: Thiago Macieira --- src/corelib/kernel/qobject.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src/corelib/kernel/qobject.cpp') diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index d3566b1081e..707c12ae0fd 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -1821,6 +1821,8 @@ void QObjectPrivate::setThreadData_helper(QThreadData *currentData, QThreadData startTimer(std::chrono::milliseconds{interval}, timerType); \endcode + \include timers-common.qdocinc negative-intervals-not-allowed + \sa timerEvent(), killTimer(), QChronoTimer, QBasicTimer */ @@ -1843,6 +1845,8 @@ int QObject::startTimer(int interval, Qt::TimerType timerType) then the timer event occurs once every time there are no more window system events to process. + \include timers-common.qdocinc negative-intervals-not-allowed + The virtual timerEvent() function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events. @@ -1887,9 +1891,10 @@ int QObject::startTimer(std::chrono::nanoseconds interval, Qt::TimerType timerTy using namespace std::chrono_literals; - if (Q_UNLIKELY(interval < 0ns)) { - qWarning("QObject::startTimer: Timers cannot have negative intervals"); - return 0; + if (interval < 0ns) { + qWarning("QObject::startTimer: negative intervals aren't allowed; the " + "interval will be set to 1ms."); + interval = 1ms; } auto thisThreadData = d->threadData.loadRelaxed(); -- cgit v1.2.3