QTimer Class Reference

#include <qtimer.h>

Inheritance diagram for QTimer:

Inheritance graph
[legend]
Collaboration diagram for QTimer:

Collaboration graph
[legend]
List of all members.

Detailed Description

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.

Example for a one second (1000 millisecond) timer (from the {widgets/analogclock}{Analog Clock} example):

widgets/analogclock/analogclock.cpp = new QTimer = new connect start(1000)

From then on, the update() slot is called every second.

You can set a timer to time out only once by calling setSingleShot(true). You can also use the static QTimer::singleShot() function to call a slot after a specified interval:

snippets/timers/timers.cpp singleShot singleShot

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the the timer's {QObject::thread()}{thread affinity} to determine which thread will emit the {QTimer::}{timeout()} signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

As a special case, a QTimer with a timeout of 0 will time out as soon as all the events in the window system's event queue have been processed. This can be used to do heavy work while providing a snappy user interface:

ZERO-CASE

= new QTimer connect start

processOneThing() will from then on be called repeatedly. It should be written in such a way that it always returns quickly (typically after processing one data item) so that Qt can deliver events to widgets and stop the timer as soon as it has done all its work. This is the traditional way of implementing heavy work in GUI applications; multithreading is now becoming available on more and more platforms, and we expect that zero-millisecond QTimers will gradually be replaced by {QThread}s.

Note that QTimer's accuracy depends on the underlying operating system and hardware. Most platforms support an accuracy of 1 millisecond, but Windows 98 supports only 55. If Qt is unable to deliver the requested number of timer clicks, it will silently discard some.

An alternative to using QTimer is to call QObject::startTimer() for your object and reimplement the QObject::timerEvent() event handler in your class (which must inherit QObject). The disadvantage is that timerEvent() does not support such high-level features as single-shot timers or signals.

Another alternative to using QTimer is to use QBasicTimer. It is typically less cumbersome than using QObject::startTimer() directly. See {Timers} for an overview of all three approaches.

Some operating systems limit the number of timers that may be used; Qt tries to work around these limitations.

See also:
QBasicTimer, QTimerEvent, QObject::timerEvent(), Timers, {Analog Clock Example}, {Wiggly Example}

Definition at line 36 of file qtimer.h.

Public Slots

void start (int msec)
void start ()
void stop ()

Signals

void timeout ()

Public Member Functions

 QTimer (QObject *parent=0)
 ~QTimer ()
bool isActive () const
int timerId () const
void setInterval (int msec)
int interval () const
void setSingleShot (bool singleShot)
bool isSingleShot () const

Static Public Member Functions

static void singleShot (int msec, QObject *receiver, const char *member)

Protected Member Functions

void timerEvent (QTimerEvent *)

Private Member Functions

int startTimer (int)
void killTimer (int)

Private Attributes

int id
int inter
int del
uint single: 1
uint nulltimer: 1


Constructor & Destructor Documentation

QTimer::QTimer ( QObject parent = 0  )  [explicit]

Constructs a timer with the given parent.

Definition at line 119 of file qtimer.cpp.

00120     : QObject(parent), id(INV_TIMER), inter(0), del(0), single(0), nulltimer(0)
00121 {
00122 }

QTimer::~QTimer (  ) 

Destroys the timer.

Definition at line 141 of file qtimer.cpp.

References INV_TIMER, and stop().

00142 {
00143     if (id != INV_TIMER)                        // stop running timer
00144         stop();
00145 }


Member Function Documentation

bool QTimer::isActive (  )  const [inline]

Returns true if the timer is running (pending); otherwise returns false.

Definition at line 48 of file qtimer.h.

Referenced by QWidgetAnimator::animate(), QWidgetAnimator::animating(), Q3NetworkOperation::arg(), Q3TextEdit::contentsMousePressEvent(), Q3TextEdit::contentsMouseReleaseEvent(), Q3ListBox::doLayout(), Q3IconView::ensureItemVisible(), Q3NetworkOperation::errorCode(), TabbedBrowser::eventFilter(), QComboBoxPrivateContainer::eventFilter(), Q3TextEdit::handleMouseMove(), Q3IconView::insertItem(), CannonField::isShooting(), Q3ListBox::itemRect(), Q3IconView::keyPressEvent(), Q3ComboBox::keyPressEvent(), Q3ListBox::keyPressEvent(), Skin::mouseMoveEvent(), Q3NetworkOperation::operation(), Q3TextEdit::optimDoAutoScroll(), Q3TextEdit::optimMouseReleaseEvent(), Q3NetworkOperation::protocolDetail(), Q3NetworkOperation::raw(), Q3NetworkOperation::rawArg(), Q3FileDialog::rereadDir(), Q3ListBox::resizeEvent(), Q3IconView::resizeEvent(), Q3NetworkOperation::setArg(), Q3IconView::setContentsPos(), Q3NetworkOperation::setErrorCode(), Q3NetworkOperation::setProtocolDetail(), Q3NetworkOperation::setRawArg(), KAsteroidsView::setShield(), Q3NetworkOperation::setState(), CannonField::shoot(), Q3ScrollView::startDragAutoScroll(), Q3ListViewItem::startRename(), Q3NetworkOperation::state(), and Q3ListView::updateDirtyItems().

00048 { return id >= 0; }

int QTimer::timerId (  )  const [inline]

Returns the ID of the timer if the timer is running; otherwise returns -1.

Definition at line 49 of file qtimer.h.

References id.

00049 { return id; }

void QTimer::setInterval ( int  msec  ) 

Definition at line 340 of file qtimer.cpp.

References inter, INV_TIMER, QObject::killTimer(), and QObject::startTimer().

Referenced by Connection::Connection(), TabbedBrowser::init(), Launcher::Launcher(), PeerManager::PeerManager(), QMainWindowLayout::QMainWindowLayout(), QWidgetAnimator::QWidgetAnimator(), SettingsTree::SettingsTree(), and start().

00341 {
00342     inter = msec;
00343     if (id != INV_TIMER) {                        // create new timer
00344         QObject::killTimer(id);                        // restart timer
00345         id = QObject::startTimer(msec);
00346     }
00347 }

Here is the call graph for this function:

int QTimer::interval (  )  const [inline]

Definition at line 52 of file qtimer.h.

Referenced by QShMemViewProtocol::rate(), and QMMapViewProtocol::rate().

00052 { return inter; }

void QTimer::setSingleShot ( bool  singleShot  )  [inline]

Definition at line 87 of file qtimer.h.

References single.

Referenced by qdesigner_internal::FormWindow::init(), TabbedBrowser::init(), Launcher::Launcher(), QComboBoxPrivateContainer::QComboBoxPrivateContainer(), QMainWindowLayout::QMainWindowLayout(), QMoviePrivate::QMoviePrivate(), and Skin::Skin().

00087 { single = asingleShot; }

bool QTimer::isSingleShot (  )  const [inline]

Definition at line 55 of file qtimer.h.

00055 { return single; }

void QTimer::singleShot ( int  msec,
QObject receiver,
const char *  member 
) [static]

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.

Example:

        #include <QApplication>
        #include <QTimer>

        int main(int argc, char *argv[])
        {
            QApplication app(argc, argv);
            QTimer::singleShot(600000, &app, SLOT(quit()));
            ...
            return app.exec();
        }

This sample program automatically terminates after 10 minutes (600,000 milliseconds).

The receiver is the receiving object and the member is the slot. The time interval is msec milliseconds.

See also:
start()

Definition at line 312 of file qtimer.cpp.

Referenced by QFtpPrivate::addCommand(), Q3Ftp::addCommand(), QGraphicsScene::addItem(), PreviewDialog::addPage(), Q3Http::addRequest(), QGraphicsScenePrivate::addToIndex(), MainWindow::addTorrent(), TorrentClientPrivate::callPeerConnector(), ChatDialog::ChatDialog(), Q3ProcessManager::cleanup(), QDesignerFormWindow::closeEvent(), TabbedBrowser::closeTab(), HelpDialog::currentTabChanged(), Q3DataTable::endEdit(), Q3FileDialog::eventFilter(), GradientWidget::GradientWidget(), QDesigner::initialize(), MainWindow::MainWindow(), Q3ComboBox::mousePressEvent(), Screenshot::newScreenshot(), DisplayWidget::paintEvent(), QGraphicsItem::prepareGeometryChange(), Q3SyntaxHighlighter::Q3SyntaxHighlighter(), Pong::quit(), Client::readFortune(), QGraphicsScenePrivate::removeFromIndex(), QGraphicsScenePrivate::resetIndex(), RateController::scheduleTransfer(), QSyntaxHighlighter::setDocument(), PreviewDialog::setNumberOfPages(), Oubliette::showEvent(), qdesigner_internal::QtGradientStopsEditorPrivate::slotCurrentStopChanged(), qdesigner_internal::QtGradientStopsEditorPrivate::slotStopMoved(), qdesigner_internal::QtGradientStopsEditorPrivate::slotStopSelected(), TrackerClient::start(), Q3FileDialog::stopCopy(), Q3SpinWidget::timerDone(), Q3DnsManager::transmitQuery(), Q3Socket::tryConnection(), Oubliette::tryMove(), QGraphicsScene::update(), MainWindow::updateDownloadRate(), and MainWindow::updateUploadRate().

00313 {
00314     if (receiver && member)
00315         (void) new QSingleShotTimer(msec, receiver, member);
00316 }

void QTimer::start ( int  msec  )  [slot]

Starts or restarts the timer with a timeout interval of msec milliseconds.

Definition at line 189 of file qtimer.cpp.

References setInterval(), and start().

Referenced by QAbstractSocketPrivate::_q_connectToNextAddress(), QMoviePrivate::_q_loadNextFrame(), QDesignerMenu::actionEvent(), Q3NetworkProtocol::addOperation(), AnalogClock::AnalogClock(), QWidgetAnimator::animate(), Q3NetworkOperation::arg(), qdesigner_internal::FormWindow::checkSelection(), Q3IconView::clear(), Q3ListView::contentsDragEnterEvent(), Q3ListView::contentsDragMoveEvent(), Q3TextEdit::contentsMouseDoubleClickEvent(), Q3ListView::contentsMouseMoveEvent(), Q3Table::contentsMouseMoveEvent(), Q3TextEdit::contentsMousePressEvent(), Q3ListView::contentsMouseReleaseEventEx(), WidgetGallery::createProgressBar(), QDesignerMenu::deactivateMenu(), Q3Table::delayedUpdateGeometries(), DigitalClock::DigitalClock(), Q3ListView::doAutoScroll(), Q3TableHeader::doAutoScroll(), Q3IconView::doAutoScroll(), Q3Table::doAutoScroll(), Q3ScrollView::doDragAutoScroll(), Q3FileDialog::doMimeTypeLookup(), Q3TableHeader::doSelection(), QDesignerMenu::dragMoveEvent(), Q3ListView::drawContentsOffset(), qdesigner_internal::FormWindow::emitSelectionChanged(), Launcher::enableLaunching(), Q3NetworkOperation::errorCode(), Q3TextEdit::eventFilter(), TabbedBrowser::find(), Q3TextEdit::formatMore(), Q3NetworkOperation::free(), Q3TextEdit::handleMouseMove(), Q3IconView::insertItem(), Q3ListView::keyPressEvent(), Q3IconView::keyPressEvent(), Q3ComboBox::keyPressEvent(), Q3ListBox::keyPressEvent(), Q3TextEdit::keyPressEvent(), main(), Skin::mouseMoveEvent(), Q3ListBox::mouseMoveEvent(), Q3DockWindowHandle::mouseReleaseEvent(), KAsteroidsView::newShip(), Q3NetworkOperation::operation(), Q3TextEdit::optimDoAutoScroll(), Q3NetworkProtocol::processNextOperation(), Connection::processReadyRead(), Q3NetworkOperation::protocolDetail(), Q3DnsManager::Q3DnsManager(), Q3NetworkOperation::raw(), Q3NetworkOperation::rawArg(), Q3ListView::repaintItem(), Q3ScrollView::resizeContents(), Q3ScrollView::resizeEvent(), qdesigner_internal::FormWindow::resizeEvent(), Launcher::resizeEvent(), Q3TableHeader::resizeEvent(), Q3ListBox::resizeEvent(), Q3IconView::resizeEvent(), Q3FileDialog::resortDir(), QRollEffect::run(), QAlphaWidget::run(), QPollingFileSystemWatcherEngine::run(), QVFbMouseLinuxTP::sendMouseData(), QMainWindowLayout::separatorMove(), Q3Canvas::setAdvancePeriod(), Q3NetworkOperation::setArg(), SettingsTree::setAutoRefresh(), Q3FileDialogQFileListView::setCurrentDropItem(), QFileListBox::setCurrentDropItem(), Q3ListBox::setCurrentItem(), Q3NetworkOperation::setErrorCode(), Q3ProgressDialog::setMinimumDuration(), Q3ListView::setOpen(), Q3ProgressDialog::setProgress(), Q3NetworkOperation::setProtocolDetail(), QShMemViewProtocol::setRate(), QMMapViewProtocol::setRate(), Q3NetworkOperation::setRawArg(), SettingsTree::setSettingsObject(), Q3Dns::setStartQueryTimer(), Q3NetworkOperation::setState(), Q3Canvas::setUpdatePeriod(), Q3NetworkProtocol::setUrl(), ShapedClock::ShapedClock(), CannonField::shoot(), Launcher::showExampleSummary(), QDesignerMenu::showSubMenu(), Skin::skinKeyRepeat(), QFDProgressAnimation::start(), PeerManager::startBroadcasting(), Sender::startBroadcasting(), Q3ScrollView::startDragAutoScroll(), Skin::startPress(), Q3SpinWidgetPrivate::startTimer(), Q3NetworkOperation::state(), Q3DnsManager::transmitQuery(), Q3ListBox::triggerUpdate(), Q3ListView::triggerUpdate(), Q3ListBox::updateItem(), Q3TableHeader::updateStretches(), QFileListBox::viewportMousePressEvent(), Q3FileDialogQFileListView::viewportMousePressEvent(), and WorldTimeClock::WorldTimeClock().

00190 {
00191     setInterval(msec);
00192     start();
00193 }

void QTimer::start (  )  [slot]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Starts or restarts the timer with the timeout specified in interval.

If singleShot is true, the timer will be activated only once.

Definition at line 177 of file qtimer.cpp.

References inter, INV_TIMER, nulltimer, single, QObject::startTimer(), and stop().

Referenced by start().

00178 {
00179     if (id != INV_TIMER)                        // stop running timer
00180         stop();
00181     nulltimer = (!inter && single);
00182     id = QObject::startTimer(inter);
00183 }

void QTimer::stop (  )  [slot]

Stops the timer.

See also:
start()

Definition at line 221 of file qtimer.cpp.

References INV_TIMER, and QObject::killTimer().

Referenced by QAbstractSocketPrivate::_q_testConnection(), Q3IconView::adjustItems(), QWidgetAnimator::animate(), QWidgetAnimator::animationStep(), Q3NetworkOperation::arg(), QFileListBox::changeDirDuringDrag(), Q3FileDialogQFileListView::changeDirDuringDrag(), Q3IconView::changeEvent(), Q3ListBox::changeEvent(), Q3ListView::changeEvent(), Q3TextEdit::changeEvent(), qdesigner_internal::FormWindow::checkSelectionNow(), Q3ListView::clear(), Launcher::closeEvent(), QDesignerMenu::closeMenuChain(), Q3ListView::contentsDragLeaveEvent(), Q3ListView::contentsDragMoveEvent(), Q3ListView::contentsDropEvent(), Q3ListView::contentsMouseDoubleClickEvent(), Q3ListView::contentsMouseMoveEvent(), Q3Table::contentsMouseMoveEvent(), Q3TextEdit::contentsMouseMoveEvent(), Q3IconView::contentsMousePressEventEx(), Q3TextEdit::contentsMouseReleaseEvent(), Q3Table::contentsMouseReleaseEvent(), Q3IconView::contentsMouseReleaseEvent(), Q3ListView::contentsMouseReleaseEventEx(), Q3FileDialogQFileListView::contentsMoved(), QFileListBox::contentsMoved(), Q3IconView::doAutoScroll(), Q3FileDialog::doMimeTypeLookup(), QFileListBox::doubleClickTimeout(), Q3FileDialogQFileListView::doubleClickTimeout(), QDesignerMenu::dragLeaveEvent(), Q3ListView::drawContentsOffset(), QDesignerMenu::dropEvent(), Skin::endPress(), Q3NetworkOperation::errorCode(), TabbedBrowser::eventFilter(), Q3TextEdit::eventFilter(), QComboBoxPrivateContainer::eventFilter(), TabbedBrowser::find(), QDesignerMenu::handleKeyPressEvent(), Q3TextEdit::handleMouseMove(), QDesignerMenu::handleMousePressEvent(), Q3IconView::insertItem(), QMoviePrivate::jumpToFrame(), Q3IconView::keyPressEvent(), Q3ComboBox::keyPressEvent(), Q3ListBox::keyPressEvent(), Q3TextEdit::keyPressEvent(), Launcher::launchExample(), Q3DockWindowHandle::mouseDoubleClickEvent(), Q3TableHeader::mouseReleaseEvent(), CannonField::moveShot(), Launcher::newPage(), Q3ListView::openFocusItem(), Q3NetworkOperation::operation(), Q3TextEdit::optimDoAutoScroll(), Q3TextEdit::optimMouseReleaseEvent(), Q3NetworkProtocol::processNextOperation(), Q3NetworkOperation::protocolDetail(), Q3NetworkOperation::raw(), Q3NetworkOperation::rawArg(), QAlphaWidget::render(), Q3FileDialog::rereadDir(), Q3ProgressDialog::reset(), QMoviePrivate::reset(), QAbstractSocketPrivate::resetSocketLayer(), Q3TableHeader::resizeEvent(), Q3ListBox::resizeEvent(), Q3IconView::resizeEvent(), Q3FileDialog::resortDir(), CannonField::restartGame(), QRollEffect::scroll(), QVFbMouseLinuxTP::sendMouseData(), Q3Canvas::setAdvancePeriod(), Q3NetworkOperation::setArg(), SettingsTree::setAutoRefresh(), Q3FileDialogQFileListView::setCurrentDropItem(), QFileListBox::setCurrentDropItem(), Q3NetworkOperation::setErrorCode(), CannonField::setGameOver(), Q3ProgressDialog::setMinimumDuration(), Q3NetworkOperation::setProtocolDetail(), QShMemViewProtocol::setRate(), QMMapViewProtocol::setRate(), Q3NetworkOperation::setRawArg(), SettingsTree::setSettingsObject(), KAsteroidsView::setShield(), Q3NetworkOperation::setState(), Q3Canvas::setUpdatePeriod(), Q3ListView::showEvent(), Q3ProgressDialog::showEvent(), Launcher::showExampleSummary(), QDesignerMenu::showLineEdit(), Launcher::showParentPage(), QDesignerMenu::showSubMenu(), QDesignerMenu::slotAdjustSizeNow(), QDesignerMenu::slotDeactivateNow(), QDesignerMenu::slotShowSubMenuNow(), Q3IconView::slotUpdate(), start(), Q3ListViewItem::startRename(), Q3NetworkOperation::state(), Q3ScrollView::stopDragAutoScroll(), Q3SpinWidgetPrivate::stopTimer(), Q3ListViewItem::takeItem(), timerEvent(), Q3FileDialog::urlStart(), Q3FileDialogQFileListView::viewportDragLeaveEvent(), QFileListBox::viewportDragLeaveEvent(), QFileListBox::viewportDragMoveEvent(), Q3FileDialogQFileListView::viewportDragMoveEvent(), Q3FileDialogQFileListView::viewportDropEvent(), QFileListBox::viewportDropEvent(), Q3FileDialogQFileListView::viewportMouseDoubleClickEvent(), QFileListBox::viewportMouseDoubleClickEvent(), QFileListBox::viewportMouseMoveEvent(), Q3FileDialogQFileListView::viewportMouseMoveEvent(), Q3Table::windowActivationChange(), Q3NetworkProtocolPrivate::~Q3NetworkProtocolPrivate(), and ~QTimer().

00222 {
00223     if (id != INV_TIMER) {
00224         QObject::killTimer(id);
00225         id = INV_TIMER;
00226     }
00227 }

void QTimer::timeout (  )  [signal]

This signal is emitted when the timer times out.

See also:
interval, start(), stop()

Referenced by timerEvent().

void QTimer::timerEvent ( QTimerEvent e  )  [protected, virtual]

Reimplemented from QObject.

Definition at line 233 of file qtimer.cpp.

References emit, id, single, stop(), timeout(), and QTimerEvent::timerId().

00234 {
00235     if (e->timerId() == id) {
00236         if (single)
00237             stop();
00238         emit timeout();
00239     }
00240 }

Here is the call graph for this function:

int QTimer::startTimer ( int   )  [inline, private]

Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.

A timer event will occur every interval milliseconds until killTimer() is called. If interval is 0, then the timer event occurs once every time there are no more window system events to process.

The virtual timerEvent() function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.

If multiple timers are running, the QTimerEvent::timerId() can be used to find out which timer was activated.

Example:

        class MyObject : public QObject
        {
            Q_OBJECT

        public:
            MyObject(QObject *parent = 0);

        protected:
            void timerEvent(QTimerEvent *event);
        };

        MyObject::MyObject(QObject *parent)
            : QObject(parent)
        {
            startTimer(50);     // 50-millisecond timer
            startTimer(1000);   // 1-second timer
            startTimer(60000);  // 1-minute timer
        }

        void MyObject::timerEvent(QTimerEvent *event)
        {
            qDebug() << "Timer ID:" << event->timerId();
        }

Note that QTimer's accuracy depends on the underlying operating system and hardware. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

The QTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QTimer and less clumsy than using timer IDs directly.

See also:
timerEvent(), killTimer(), QTimer::singleShot()

Reimplemented from QObject.

Definition at line 79 of file qtimer.h.

00079 { return -1;}

void QTimer::killTimer ( int   )  [inline, private]

Kills the timer with timer identifier, id.

The timer identifier is returned by startTimer() when a timer event is started.

See also:
timerEvent(), startTimer()

Reimplemented from QObject.

Definition at line 80 of file qtimer.h.

00080 {}


Member Data Documentation

int QTimer::id [private]

Definition at line 82 of file qtimer.h.

Referenced by timerEvent().

int QTimer::inter [private]

Definition at line 82 of file qtimer.h.

Referenced by setInterval(), and start().

int QTimer::del [private]

Definition at line 82 of file qtimer.h.

uint QTimer::single [private]

Definition at line 83 of file qtimer.h.

Referenced by setSingleShot(), start(), and timerEvent().

uint QTimer::nulltimer [private]

Definition at line 84 of file qtimer.h.

Referenced by start().


The documentation for this class was generated from the following files:
Generated on Thu Mar 15 19:33:57 2007 for Qt 4.2 User's Guide by  doxygen 1.5.1