使用Qt,其中工作线程创建新的GUI元素 [英] Using Qt where worker thread creates new GUI elements

查看:656
本文介绍了使用Qt,其中工作线程创建新的GUI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会保持代码简单,让你们可以看到我想做什么;)
我知道所有的锁定问题,等我试图找出如何信号和插槽播放线程。

I will keep the code simple so that you guys can see what I'm trying to do ;) I am aware of all of the locking issues, etc. I'm trying to figure out how signals and slots play with threads.

在main.cpp中:

In 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();
}

假设信号和插槽已正确设置在头文件经过测试,他们是)。现在,这里是问题:

Assume that the signals and slots were properly set up in the header files (I've tested and they are). Now, here's the issue:

在MyReceiver.cpp中:

In 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)提出的情况下?

The question is: Because the MyReceiver object was created in main(), which is on the main thread, does that mean that the slots (e.g., gotit()) will run on the main thread and are therefore safe for doing GUI stuff? Even in cases where the signal was raised from a different QThread (like MyConsole in this example)?

有更好的方法允许工作线程与GUI例如,Obj-C / Cocoa有一个在主线程上发送消息类型的方法)。什么是Qt方式这样做?

Is there a better way to allow worker threads to interact with the GUI (for example, Obj-C/Cocoa have a "send message on main thread" type of approach). What is "The Qt way" of doing this?

提前感谢!

推荐答案

Qt方式从一个线程发出信号并在不同的线程接收它是使用一个排队的连接

The "Qt way" to emit a signal from one thread and receive it in a different thread is to use a Queued connection

connect( obj, SIGNAL(foo()), other_obj, SLOT(bar()), Qt::QueuedConnection )

从Qt :: QueuedConnection的Qt文档:

From the Qt documentation for Qt::QueuedConnection:


当控件返回事件时调用槽循环的接收者的线程。该插槽在接收者的线程中执行。

The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

这篇关于使用Qt,其中工作线程创建新的GUI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆