#ifndef CLOCKTHREAD_H
#define CLOCKTHREAD_H
#include <QString>
#include <QThread>
// clock/clockthread.h
class ClockThread : public QThread
{
Q_OBJECT
signals:
void sendTime(QString time);
private:
void run();
QString m_lastTime;
private slots:
void timerHit();
};
#endif // CLOCKTHREAD_H
=================
#include <QtGui>
#include "clockthread.h"
//This class starts another thread where it emits a signal for every new second.
// clock/clockthread.cpp
void ClockThread::run()
{
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(timerHit()), Qt::DirectConnection);
timer.setInterval(10);
timer.start(); // puts one event in the threads event queue
exec();
timer.stop();
}
void ClockThread::timerHit()
{
QString newTime= QDateTime::currentDateTime().toString("ddd MMMM d yy, hh:mm:ss");
if(m_lastTime != newTime ){
m_lastTime = newTime;
emit sendTime(newTime) ;
}
}
=============================
#include <QtGui>
#include "clockthread.h"
//A clock that does time formatting in another thread
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build gui
QWidget widget;
QLabel *label = new QLabel;
QHBoxLayout *layout = new QHBoxLayout(&widget);
layout->addWidget(label);
widget.setWindowTitle("clock");
//instantiate thread object
ClockThread clockThread;
QObject::connect(&clockThread, SIGNAL(sendTime(QString)), label, SLOT(setText(QString)), Qt::QueuedConnection);
clockThread.start();
widget.show();
app.exec();
clockThread.quit();
clockThread.wait();
return 0;
}