线程池QThreadPool实现多线程, 信号槽实现异步线程刷新UI控件
启动效果
调用是没有问题
这里本来是想打印出线程ID, 不知道怎么用
QString(QThread::currentThread()
输出, 怎么转换成QString
文档结构
线程类
printtask.h
#ifndef PRINTTASK_H
#define PRINTTASK_H
#include <QObject>
#include <QRunnable>
class PrintTask : public QObject, public QRunnable
{
Q_OBJECT
signals:
void notify(QString);
public:
PrintTask();
~PrintTask();
protected:
void run();
signals:
//注意!要使用信号,采用QObejct 和 QRunnable多继承,记得QObject要放在前面
void mySignal();
};
#endif // PRINTTASK_H
printtask.cpp
#include "printtask.h"
#include <QThread>
#include <iostream>
using std::cout;
using std::endl;
PrintTask::PrintTask()
{
}
PrintTask::~PrintTask()
{
}
//线程真正执行的内容
void PrintTask::run()
{
QString printf;
printf = tr("PrintTask run called");
//printf.append(QString(QThread::currentThread()));
//cout << "PrintTask run 被调用,调用线程ID为:" << QThread::currentThread() << endl;
emit notify(printf);
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void notify(QString print);
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "printtask.h"
#include <QThread>
#include <iostream>
using std::cout;
using std::endl;
PrintTask::PrintTask()
{
}
PrintTask::~PrintTask()
{
}
//线程真正执行的内容
void PrintTask::run()
{
QString printf;
printf = tr("PrintTask run called");
//printf.append(QString(QThread::currentThread()));
//cout << "PrintTask run 被调用,调用线程ID为:" << QThread::currentThread() << endl;
emit notify(printf);
}
这里的传送类型可以随便设置, int 或者 QString.