3

I am trying to run a background thread (qthread) that needs to monitor a checkbox in the gui and it will not run! It builds but during runtime i get this error:

"Unhandled exception at 0x0120f494 in program.exe: 0xC0000005: Access violation reading location 0xcdcdce55."

and it breaks on the "connect" line. What is the best way to do this?

guiclass::guiclass(){
    thread *t = new thread();
}

thread::thread(){
     guiclass *c = new guiclass();
     connect(c->checkBox, SIGNAL(stateChanged(int)), this, SLOT(checked(int)));

     ....
     start work
     ....
}

bool thread::checked(int c){
     return(c==0);
}

void thread::run(){

    if(checked()){
        do stuff
    }
}
JonnyCplusplus
  • 881
  • 3
  • 12
  • 22
  • where are you initializing `c->checkBox`? how are you dealing with the fact that `new guiclass` calls `new thread` calls `new guiclass` calls `new thread` calls `new guiclass`calls `new thread` calls `new guiclass` ... – Mat Jun 08 '11 at 20:42
  • Clearly I am not dealing with the threads calling each other, looks like my problem. So, how would i monitor the guiclass without creating a guiclass object? – JonnyCplusplus Jun 08 '11 at 20:47

1 Answers1

3

The event queue of any QThread object is actually handled by the thread that started it, which is quite unintuitive. The common solution is to create a "handler" object (derived from QObject), associate it with your worker thread by calling moveToThread, and then bind the checkbox signal to a slot of this object.

The code looks something like this:

class ObjectThatMonitorsCheckbox : public QObject
{
     Q_OBJECT
     // ...

public slots:
     void checkboxChecked(int checked);
}

In the code that creates the thread:

QThread myWorkerThread;

ObjectThatMonitorsCheckbox myHandlerObject;

myHandlerObject.moveToThread(&myworkerThread);
connect(c->checkBox, SIGNAL(stateChanged(int)), &myHandlerObject, 
    SLOT(checkboxChecked(int)));

myWorkerThread.start();

One key point: Don't subclass QThread -- all the actual work is done in your handler object.

Hope this helps!

See also: Qt: Correct way to post events to a QThread?

Community
  • 1
  • 1
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281