Reputation: 39
In a QT app, I want to start a loop inside a qthread that reads 2 different sounds (it's a metronome).
I have a function with my process. I want to start it when I click on a button and stop it with another one.
The problem is, when I start it, my app doesn't respond, I can't click on the stop button. I have to stop the app.
#include <QSound>
#include <QEventLoop>
ClickThread::ClickThread(): highClickFile("://high_click.wav"), lowClickFile("://low_click.wav"), isRunning(false)
{
this->highClick = new QSound(highClickFile);
this->lowClick = new QSound(lowClickFile);
this->setPeriod(120);
}
void ClickThread::run()
{ QTimer *timer = new QTimer();
timer ->moveToThread(this);
timer->connect(timer, SIGNAL(timeout()),this, SLOT(process()));
timer ->start();
exec();
}
void ClickThread::process(){
highClick->play();
QThread::msleep(period);
highClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
}
void ClickThread::setIsRunning(bool set)
{
this->isRunning=set;
}
void ClickThread::setPeriod(unsigned long bpm)
{
this->period = 60000/bpm;
}
Thx for your answers
Upvotes: 0
Views: 721
Reputation: 333
Stop using QTimer.
The QTimer you have currently is default to a timeout interval of 0. That is going to stuff up the event queue with infinite calls to process(), which will cause serious problems.
You should use this while loop instead:
stopPlaying = false;
while(stopPlaying == false)
{
process();
}
The boolean stopPlaying variable should be declared in your "ClickThread" class definition and used by your stop button to cause the thread to drop out of the loop, terminating the thread.
Upvotes: 1