#include <QCoreApplication>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QDebug>
{
Q_OBJECT
int m_continue;
public:
Worker() : m_continue(1)
{
qDebug() << "Worker::Ctor";
QTimer::singleShot(7000,
this,
SLOT(discontinue
()));
// Expecting to call discontinue() after 7 secs. }
~Worker() { qDebug() << "Worker::Dtor"; }
private slots:
void doWork()
{
while(m_continue)
{
qDebug
() <<
QTime::currentTime().
toString("HH:mm");
}
emit done();
qDebug() << "Done!";
}
void discontinue()
{
qDebug() << "Aborting ...";
m_continue = 0;
}
signals:
void done();
};
int main(int argc, char *argv[])
{
Worker worker;
worker.moveToThread(&thread);
QCoreApplication::connect(&worker,
SIGNAL(done
()),
&worker,
SLOT(deleteLater
()));
QCoreApplication::connect(&thread,
SIGNAL(finished
()),
&thread,
SLOT(deleteLater
()));
thread.start();
return a.exec();
}
#include "main.moc"
#include <QCoreApplication>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QDebug>
class Worker : public QObject
{
Q_OBJECT
int m_continue;
public:
Worker() : m_continue(1)
{
qDebug() << "Worker::Ctor";
QTimer::singleShot(7000, this, SLOT(discontinue())); // Expecting to call discontinue() after 7 secs.
}
~Worker() { qDebug() << "Worker::Dtor"; }
private slots:
void doWork()
{
while(m_continue)
{
qDebug() << QTime::currentTime().toString("HH:mm");
QThread::sleep(2);
}
emit done();
qDebug() << "Done!";
}
void discontinue()
{
qDebug() << "Aborting ...";
m_continue = 0;
}
signals:
void done();
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThread thread;
Worker worker;
worker.moveToThread(&thread);
QCoreApplication::connect(&thread, SIGNAL(started()), &worker, SLOT(doWork()));
QCoreApplication::connect(&worker, SIGNAL(done()), &thread, SLOT(quit()));
QCoreApplication::connect(&worker, SIGNAL(done()), &worker, SLOT(deleteLater()));
QCoreApplication::connect(&thread, SIGNAL(finished()), &thread, SLOT(deleteLater()));
thread.start();
return a.exec();
}
#include "main.moc"
To copy to clipboard, switch view to plain text mode
Bookmarks