自定義一個QThreadPool,N個線程QRunnable,線程和Widget通過QMetaObject::invokeMethod交互。
QRunnable非繼承自QObject,所以不可以用信號和槽的方式和Widget主界面交互,為了和Widget主界面交互,可以用QMetaObject::invokeMethod進行交互。
1、創建一個Widget工程,並在Widget類下定義一個QThreadPool的私有變量MyThreadPool;
2、在Widget的構造函數中設置MyThreadPool的屬性,如:setMaxThreadCount(1)等等。
3、新建一個私有槽函數 void showinfo(QString str);
4、在Widget.cpp實現該函數,將str信息顯示到界面的QLineEdit編輯框。
5、在Widget的ui界面添加一個按鈕,用於MyThreadPool創建一個任務,添加一個QLineEdit編輯框,用於顯示str。
6、為了和Widget交互,需要對QRunnable進行自定義封裝,在構造函數中將Widget指針傳遞進去。
代碼如下:
Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <math.h>
#include <QWidget>
#include <QLineEdit>
#include <QThreadPool>
//////////////////////////////////////////////////////
namespace Ui {
class Widget;
}
class Widget : public QWidget {
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_emit_Btn_clicked();
void Update_Result(QString);
private:
Ui::Widget *ui;
QThreadPool MyThreadPool;
};
Widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "qmyrunnable.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
MyThreadPool.setMaxThreadCount(1);
MyThreadPool.setParent(this);
}
Widget::~Widget()
{
MyThreadPool.waitForDone();
delete ui;
}
void Widget::Update_Result(QString str)
{
ui->lineEdit_1->setText(str);
}
void Widget::on_emit_Btn_clicked()
{
MyThreadPool.start(new QMyRunnable(this));
}
QMyRunnable.h
#ifndef QMYRUNNABLE_H
#define QMYRUNNABLE_H
#include <QTest>
#include <QRunnable>
class QMyRunnable : public QRunnable
{
public:
QMyRunnable(QObject* obj);
protected:
void run();
private:
QObject* obj;
};
QMyRunnable.cpp
#include "qmyrunnable.h"
#include "widget.h"
QMyRunnable::QMyRunnable(QObject* obj) : obj(obj)
{
}
void QMyRunnable::run()
{
QString str = QString("%1+%2=%3").arg(1).arg(1).arg(1+1);
QMetaObject::invokeMethod(obj,"Update_Result",Q_ARG(QString,str));
QTest::qWait(100);
}
main.cpp
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}