alessiop86 alessiop86 - 1 year ago 84
C++ Question

Qt thread and loop issue

this is the run method of a subclass of QThread:

void crono::Controller::run() {

//initialise timer
int *i = & this->model->seconds_elapsed;

for (*i = 0; *i < this->model->seconds_total; (*i)++) {

//calculate current seconds/minutes/hours elapsed starting from seconds_elapsed (*i)

//should display in the form the time elapsed


Beep(1000, 500); //beep when all is over


the controller updates the model values.

The QT form is opened on start, I guess in the main application thread.

The issue is that despise on debug *i=0 and seconds_total = X > 0, the loop is executed only one time, after the first time the debug halt (it does not end), the forms pops up but nothing happens.

The only thing I can guess of, is that the Controller Thread lose its priority and never gains the cpu again.

How can avoid this?

I am trying using QTimer, with bad luck.

i declared update as a public slot, and then implemented like this:

void crono::Controller::update() {


//eventually stop at some point (pointer to timer and timer->stop()?
//Beep(1000, 500);

And I inserted the QTimer in the controller (thread) object instead of the loop cycle:

void crono::Controller::run() {

//inizializzo timer
int *i = & this->modello->secondi_trascorsi;

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),this, SLOT(update()));


I do not know why, but the update() method is never called, instead of being called an infinite number of times. Why?

Answer Source

As Tim Meyer pointed out in his comment, you need to call QThread:exec() at the end of your QThread::run() implementation, this in order to start the thread's event loop, which is needed in order for the Signal/Slot mechanism to work.

However, it seems like you're doing it wrong.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download