QThread 的使用

本文详细探讨了QThread的使用,包括QThread的两种主要使用方式:子类化Thread和worker对象移动到线程。文章指出QThread并不等同于线程,而是用于管理线程的对象。通过例子解析了QThread::run和QObject::connect的工作原理,强调了自动连接和队列连接的区别。同时,文章分析了不同场景下选择不同QThread使用方式的原因,提醒开发者注意避免潜在陷阱。
摘要由CSDN通过智能技术生成

1. 引言

你会用QThread吗?有几种使用方式?这几种使用方式都在何种场景下使用?有什么需要注意的地方吗?

2. QThread 文档

上来先看 Qt 帮助文档。QThread Class 文档,详细描述的第一句话:

The QThread class provides a platform-independent way to manage threads

注意看倒数第二个单词,QThread 不等于线程,QThread 是负责管理线程的。
接下来看文档,我们清楚的知道QThread的两种使用方式。

方式一:子类化QThread,并重新实现 run() 函数
方式二:定义工作对象继承自 QObject,然后把这个工作对象move到QThread的一个对象中。

3. QThread::run 和 QObject::connect

先看下帮助文档上怎么描述这个 QThread::run 函数的:
The starting point for the thread. After calling start(), the newly created thread calls this function. The default implementation simply calls exec().
You can reimplement this function to facilitate advanced thread management. Returning from this method will end the execution of the thread.
这段英文描述的很清楚。好,下面看例子:

先看文档上的例子:

class Worker : public QObject
{
    Q_OBJECT
public:
    Worker(){}
public slots:
    void emitsig()
    {
        emit sig();
    }
signals:
    void sig();
};

class Thread : public QThread
{
    Q_OBJECT
public:
	Thread(QObject* parent=0):QThread(parent)
	{
	}

	void fun()
	{
		qDebug() << "Thread::fun threadID: " << QThread::currentThreadId();
	}
public slots:
	void slotFun()
	{
		qDebug() << "Thread::slotFun threadID: " << QThread::currentThreadId();
	}
signals:
    void sig();
protected:
	void r
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值