3

我正在尝试运行需要监视 gui 中的复选框的后台线程(qthread),但它不会运行!它构建但在运行时我收到此错误:

“program.exe 中 0x0120f494 处的未处理异常:0xC0000005:访问冲突读取位置 0xcdcdce55。”

它在“连接”线上中断。做这个的最好方式是什么?

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

1 回答 1

3

任何对象的事件队列QThread实际上都是由启动它的线程处理的,这很不直观。常见的解决方案是创建一个“处理程序”对象(从 派生QObject),通过调用将其与您的工作线程相关联moveToThread,然后将复选框信号绑定到该对象的插槽。

代码看起来像这样:

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

public slots:
     void checkboxChecked(int checked);
}

在创建线程的代码中:

QThread myWorkerThread;

ObjectThatMonitorsCheckbox myHandlerObject;

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

myWorkerThread.start();

一个关键点:不要子类QThread化——所有实际工作都在您的处理程序对象中完成。

希望这可以帮助!

另请参阅:Qt:将事件发布到 QThread 的正确方法?

于 2011-06-08T20:47:18.310 回答