Threads and QObjects

QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

QThread 派生于 QObject。QThread 会发射信号通知线程启动或终止执行任务,并且也会提供槽函数使用。

More interesting is that QObjects can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that "live" in other threads. This is possible because each thread is allowed to have its own event loop.

QObejct 可以在多线程中调用,通过信号可以调用在其它线程中的槽函数,而且可以传递事件给其它线程中的对象。这使得每个线程都有自己的事件循环成为可能。

三种情况应注意:

  • The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object (this) as the parent of an object created in the thread (since the QThread object itself was created in another thread).
  • QObject 的所有子类必须在创建parent对象的线程(thread)中创建。这意味着,永远不要将QThread对象作为在线程中创建的对象的parent对象(因为 QThread 对象本身是在另一个线程中创建的)。
  • Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.
  • 对于定时器机制和网络模块,事件驱动对象只能在单线程中调用。例如,不能在非对象线程的线程中启动定时器或连接套接字。
  • You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.
  • 程序员必须保证在销毁线程前销毁在线程中中创建的所有对象。要做到这一点很容易,只需在 run() 实现中在堆栈上创建对象即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值