#include <QDebug>#include <QThread>class Worker : public QObject{ Q_OBJECTpublic: Worker();private slots: void onTimeout();private: int counter;};
#include "worker.h"Worker::Worker(){ counter = 0;}void Worker::onTimeout(){ qDebug()<<"Worker::onTimeout get called from?: "<<QThread::currentThreadId(); counter++; //if (counter == 3) // stopTimer();}
#include <QMainWindow>#include <QDebug>#include <QThread>#include <QTimer>#include "worker.h"namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{ Q_OBJECTpublic: explicit MainWindow(QWidget *parent = 0); ~MainWindow();private: Ui::MainWindow *ui; QThread t; QTimer timer; Worker worker;private slots: void onInit(); void onStart();};
... connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(onStart()));...//------------------------------------------------------------------------------void MainWindow::onStart(){ qDebug()<<"From main thread: "<<QThread::currentThreadId(); QObject::connect(&timer, SIGNAL(timeout()), &worker, SLOT(onTimeout())); timer.start(1000); worker.moveToThread(&t); t.start();}
class Worker : public QObject{ Q_OBJECTpublic: Worker(); void start();private slots: void onTimeout(); void stop();signals: void stopTimer();private: int counter; QTimer timer;};
Worker::Worker(){ counter = 0; QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout())); QObject::connect(this, SIGNAL(stopTimer()), this, SLOT(stop()));}void Worker::start(){ timer.start(1000);}void Worker::stop(){ timer.stop();}void Worker::onTimeout(){ qDebug()<<"Worker::onTimeout get called from?: "<<QThread::currentThreadId(); counter++; if (counter == 3) { emit stopTimer(); //timer.stop(); }}
//------------------------------------------------------------------------------void MainWindow::onStart(){ qDebug()<<"From main thread: "<<QThread::currentThreadId(); worker.moveToThread(&t); worker.start(); t.start();}
C++ (Qt)QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout()), Qt::QueuedConnection);
C++ (Qt)// расчетыfor (int i = 0; i < data.size(); ++i) { DoCalc(i); if ((i % 100) == 0) // обновляем каждые 100 итераций UpdateIndicator(i);} void UpdateIndicator( int val ){ static QTime theTime = QTime::currentTime(); if (theTime.elapsed() < 300) return; theIndicator->setValue(val); theIndicator->repaint(); theTime.restart();}
C++ (Qt)detki::detki(int x){ postrelka = x;} void detki::run(){ // приоритет потока this->setPriority(QThread::IdlePriority); for (int i = postrelka; i > 0; i--) { //пауза в микросекундах this->msleep(500); emit YourSignal(QString::number(i)); } exec();}