线程池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.
本文介绍了如何利用Qt库中的QThreadPool和QRunnable来实现多线程,特别是在需要异步刷新UI控件的场景下。通过创建线程类并连接信号槽,可以实现在后台线程中执行任务并安全地更新UI。虽然在尝试打印线程ID时遇到一些困难,但整个框架已经成功地展示了线程池的工作原理。

1万+

被折叠的 条评论
为什么被折叠?



