我将保持代码简单,以便你们可以看到我正在尝试做什么;)
我知道所有锁定问题等。我试图弄清楚信号和插槽如何与线程一起使用。
在main.cpp中:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyConsole c; // Subclasses QThread and implements run()
MyReceiver r(app); // We pass app to MyReceiver for later (see below)
QObject::connect(&c, SIGNAL(sendit()),
&r, SLOT(gotit()));
c.start(); // Start the worker thread
app.exec();
}
假设信号和槽已在头文件中正确设置(我已经测试过了,确实如此)。现在,问题来了:
在 MyReceiver.cpp 中:
void MyReceiver::gotit()
{
QLabel *label = new QLabel(0, "Hello"); // Some GUI element, any will do
app.setMainWidget(*label); // Some GUI action, any will do
}
问题是:因为 MyReceiver 对象是在主线程上的 main() 中创建的,这是否意味着插槽(例如,gotit())将在主线程上运行,因此可以安全地执行 GUI 操作?即使信号是从不同的 QThread 发出的(如本例中的 MyConsole)?
有没有更好的方法来允许工作线程与 GUI 交互(例如,Obj-C/Cocoa 有“在主线程上发送消息”类型的方法)。这样做的“Qt 方式”是什么?
提前致谢!