Terminer proprement un thread
Bonjour,
je m'appuie sur l'article https://mayaposch.wordpress.com/2011...l-explanation/ pour travailler sur les threads dans Qt.
Dans mon application, un thread secondaire reçoit des données du réseau et doit mettre à jour l'IHM.
Dans un premier temps, mon appli "test unitaire" fonctionne correctement (mise à jour périodique d'un label sur l'ihm) mais je n'arrive pas à stopper proprement le thread à l'appui sur un bouton stop.
Code côté thread principal:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
//Gestion sur le clic du bouton start
void MainWindow::start_thread()
{
QThread* thread = new QThread;
WorkerThread* worker = new WorkerThread();
worker->moveToThread(thread);
//connecter le signal plus du worker au slot plus de mainWindow pour rafraîchir l'ihm
connect(worker, SIGNAL(plus()), this, SLOT(plus()));
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
//Qd le thread démarre, il démarre le workerthread
connect(thread, SIGNAL(started()), worker, SLOT(process()));
//Qd le workerthread s'arrête, il stoppe le thread
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
//c'est ce connect qui ne semble pas fonctionner...
connect(this, SIGNAL(stopThread()), worker, SLOT(running()));
thread->start();
}
// Clic sur le bouton stop. Stop le thread démarré par start_thread().
void MainWindow::stop_thread()
{
emit stopThread();
} |
Code côté thread secondaire:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
//le job dans le thread
void WorkerThread::process()
{
while(continuer == true)
{
emit plus(); //destination du thread ui pour rafraîchissement
QThread::sleep(1);
}
emit finished(); //à destination du QThread
}
//connectée au signal stopThread du thread ui
void WorkerThread::running()
{
continuer = false;
} |
Je pense que le signal stopThread est émit mais à priori je ne passe jamais dans la méthode running().
Si vous voyez d'où vient le problème, merci.