背景
使用Qt开发界面程序的时候,免不了做一些数据计算,有时候,当计算量比较大,需要耗费一定的时间。一直在界面上等待肯定不是一个好的办法。这里介绍一种多线程的处理方法。
方法
- 在界面相关的类中定义一个 QThread 指针成员变量m_oper,m_oper构造时,不要指定parent,不然m_oper就和parent处于同一个线程下了。
- 将需要处理的计算用枚举或是其他类型进行区分,这样可以根据名称处理多个不同的计算,计算时,先为m_oper传递需要的参数,然后执行m_oper->start();进行计算。
- 当m_oper计算完成之后,可通过信号通知界面类,并提供接口去为界面类提供计算结果数据。
- 界面类的槽函数在获取当处理结果时,把结果显示在界面上。这样在计算的过程中,界面就不会出现卡顿的现象。
代码示例
class FileOper : public QThread
{
signals:
void processFinished();
public:
enum Class OperType : int
{
PROCESS_INDEX = 0,
// other enums
}
void setParams(const QString& msg)
{
// send param to the thread
}
void start()
{
switch(m_type)
{
case PROCESS_INDEX :
process(); //处理界面数据的函数
emit processFinished();
break;
}
}
}
class widget : public QWidget
{
...
explicit widget(QWidget* parent = nullptr)
{
m_oper = new FileOper();
connect(m_oper,&FileOper::processFinished,
this,&widget::onProcessFinished);
}
void setParam(const QString& msg);//the thread params for calc
private slots:
void onBtnClicked()
{
m_oper->setOperType(FileOper::OperType::PROCESS_INDEX);
m_oper->setParam("the param to be calc");
m_oper->start();
}
void onProcessFinished()
{
QString result = m_oper->result();
//TODO:ui opers
}
private:
FileOper* m_oper;
};
网友评论