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
}
}
The event queue of any
QThreadobject is actually handled by the thread that started it, which is quite unintuitive. The common solution is to create a “handler” object (derived fromQObject), associate it with your worker thread by callingmoveToThread, and then bind the checkbox signal to a slot of this object.The code looks something like this:
In the code that creates the thread:
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?