JonnyCplusplus
JonnyCplusplus

Reputation: 881

Monitor Qt GUI from QThread class

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
    }
}

Upvotes: 3

Views: 955

Answers (1)

Tony the Pony
Tony the Pony

Reputation: 41397

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?

Upvotes: 3

Related Questions