#include "Timer.h"наследник от QThreadTimer::Timer(int interval) : m_interval(interval), m_startFlag(true){}Timer::~Timer(){ //delete timer; //quit();}void Timer::run(){ QTimer timer; connect(&timer, &QTimer::timeout, this, &Timer::sg_TimOut); connect(this, SIGNAL(timerStarted(int)), &timer, SLOT(start(int))); if (m_startFlag) timer.start(m_interval); exec(); //mit finished(this->thread());}void Timer::startTimer(int interval){ m_interval = interval; m_startFlag = true; emit timerStarted(interval);}void Timer::stop(){ m_startFlag = false; emit timerStoped();}void Timer::quit(){ //stop(); //QThread::quit();}
m_tmr = new Timer(1000); //класс поток для таймера m_tmr->start(); connect(m_tmr, &Timer::sg_TimOut, this, &MainForm::updateByTimer, Qt::DirecConnection); connect(m_tmr, &QThread::finished, m_tmr, &Timer::deleteLater);
C++ (Qt)class Thread : public QThread{ Q_OBJECT public: Thread(QObject*parent = 0); virtual ~Thread(); public slots: void timeOut(); protected: void run();}
C++ (Qt)Thread::Thread(QObject*parent): QThread(parent){} Thread::~Thread(){} void Thread::run(){ QTimer timer; // Qt::DirectConnection чтобы слот обрабатывался в контексте того потока из которого был выслан сигнал connect(&timer,SIGNAL(timeout()),this,SLOT(timeOut()),Qt::DirectConnection); timer.start(50); exec();} void Thread::timeOut(){// do something}
C++ (Qt)void Widget::createThread(){ if(thread == NULL){ thread = new Thread(0); thread->start(); }}
C++ (Qt) void Widget::quitThread(){ if(thread != NULL){ thread->quit(); thread->wait(); delete thread; //thread->deleteLater(); thread = NULL; }}
C++ (Qt)void Thread::run(){ QTimer timer; // Qt::DirectConnection чтобы слот обрабатывался в контексте того потока из которого был выслан сигнал connect(&timer,SIGNAL(timeout()),this,SLOT(timeOut()),Qt::DirectConnection); timer.start(50); exec();}
moveToThread(this)
C++ (Qt)void foo (){ Thread thread; thread.moveToThread( &thread ); thread.start();}
C++ (Qt)void foo (){ Thread * thread = new Thread; thread->moveToThread( thread ); thread->start();}
C++ (Qt)class Thread: public QThread{public: ~Thread () { ::std::cout << "Deleted" << ::std::endl; } virtual void run () { ::std::cout << "Before exec" << ::std::endl; exec(); ::std::cout << "After exec" << ::std::endl; }}; int main ( int argc, char ** argv ){ QCoreApplication app( argc, argv ); QThread * thread = new Thread; thread->moveToThread( thread ); thread->start(); thread->deleteLater(); thread->quit(); return app.exec();}
Before execAfter exec
Before execDeletedQThread: Destroyed while thread is still runningAfter exec