简体   繁体   English

如何从成员QThread更改QMainWindow上的Qt GUI小部件?

[英]How can I change Qt GUI widgets on a QMainWindow from a QThread which is a member?

I have my main form made Qt Designer and inheriting from QMainWindow and the UI. 我的主要表单是Qt Designer,并继承自QMainWindow和UI。 I need to have other threads running, and I need those threads to change things on the main form, eg progress bars, LCDs. 我需要运行其他线程,并且需要那些线程来更改主窗体上的内容,例如进度条,LCD。

How do I give the other thread access to the widgets on the main form? 如何让其他线程访问主窗体上的小部件?

Thanks for any help. 谢谢你的帮助。

Using signal/slots. 使用信号/插槽。 Trolltech introduces from 4.xa threadsafe mechanism for signaling using for example the Qt::BlockingQueuedConnection parameter in connect() function. Trolltech从4.xa引入了线程安全机制,用于使用例如connect()函数中的Qt :: BlockingQueuedConnection参数进行信号传递。

For more details see: http://lists.trolltech.com/qt-interest/2007-03/thread00260-0.html 有关更多详细信息,请参见: http : //lists.trolltech.com/qt-interest/2007-03/thread00260-0.html

As Flavius Suciu has mentioned, you can use a cross-thread signal/slot connection. 正如Flavius Suciu所提到的,您可以使用跨线程信号/插槽连接。 They can also carry arguments, however, if you don't pass just fundamental types or Qt types as signal parameters but, say, your own custom struct , you need to tell Qt about them this way: 它们也可以带有参数,但是,如果您不只是传递基本类型或Qt类型作为信号参数,而是说您自己的自定义struct ,则需要通过以下方式将它们告知Qt:

namespace MyNamespace { // if any...
    struct MyClass { /* ... */ };
} // if any
Q_DECLARE_METATYPE( MyNamespace::MyClass )

This allows MyClass to be stuffed into QVariant s, which is what Qt uses internally to ship copies of the signal arguments over thread boundaries. 这允许将MyClass填充到QVariant ,这是Qt在内部使用它在线程边界上传递信号参数的副本的方法。

You might also need to call 您可能还需要打电话

qRegisterMetaType<MyNamespace::MyClass>();

somewhere it's bound to be executed before any signal/slot cross-thread connection is attempted (eg in main() , or your QThread subclass constructor). 一定要在尝试任何信号/插槽跨线程连接之前执行它(例如,在main()QThread子类构造函数中)。

See the docs of Q_DECLARE_METATYPE 请参阅Q_DECLARE_METATYPE的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM