Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor Qt GUI from QThread class

Tags:

c++

qt

qthread

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
    }
}
like image 863
JonnyCplusplus Avatar asked Jan 01 '26 12:01

JonnyCplusplus


1 Answers

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?

like image 64
Tony the Pony Avatar answered Jan 03 '26 02:01

Tony the Pony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!