我们知道c++使用线程很方便
#include <thread>
void func()
{
std::cout<<"hello"<<std::endl;
}
int main()
{
std::thread t(func);
t.join(); //阻塞执行 ,等待函数执行完毕才会执行后面的操作
std::thread t1(func);
t1.detach(); //放在后台执行
}
qt有一个类叫Qthread
网上有很多方法,包括qt的官方文档,写的是尽量使用movetothread,需要创建一个qobject类,这个类中放耗时函数。然后创建Qthread,通过stdmovetothread将耗时函数操作在另外一条线程中执行。需要在析构函数中进行删除。我觉得这样写不是很方便。
当我只需要执行一个函数,却需要创建一个类,很麻烦
qthread进行操作的是run函数,我觉得继承写就是可以的
class EP_JobShotIndexThread :public QThread
{
Q_OBJECT
public:
EP_JobShotIndexThread(EP_JobWgt *pwgt, QList<QString> i_idList, QList<QString> i_norepeatList)
{
m_pJobWgt = pwgt;
m_ShotIDList = i_idList;
m_noRepeatShotIDList = i_norepeatList;
}
private:
void run()
{
m_pJobWgt->SetShotDataIndex(m_ShotIDList, m_noRepeatShotIDList);
}
EP_JobWgt* m_pJobWgt = nullptr;
QList<QString> m_ShotIDList;
QList<QString> m_noRepeatShotIDList;
};
我的耗时函数是
void EP_JobWgt::SetShotDataIndex(QList<QString> i_idList, QList<QString> i_norepeatList)
{
for (auto i : i_norepeatList)
{
int index = 0;
for (int j = 0; j < i_idList.size(); j++)
{
if (i == i_idList[j])
{
index = index + 1;
m_pShotListTableModel->setData(m_pShotListTableModel->index(j, 3), index);
}
}
}
}
这个进行测试,是需要大概15秒左右的时间才能执行完成。所以我将他放在线程中执行。
使用起来也很方便
EP_JobShotIndexThread* thread = new EP_JobShotIndexThread(this,StrIdList, norepeatIDList);
thread->start();
ヾ( ̄▽ ̄)ByeBye