文章简单实现 Qt 多线程实现 object继承方式
开一个线程,打印线程ID号
结果

界面

开一个线程,打印线程ID号
创建一个类 mythread 继承 object
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class mythread:public QObject
{
Q_OBJECT
public:
explicit mythread(QObject *parent = nullptr);
signals:
void ID(QString ID);
public slots:
void test();
};
#endif // MYTHREAD_Hmythread.cpp
#include "mythread.h"
#include<QDebug>
#include<QThread>
mythread::mythread(QObject *parent)
:QObject(parent)
{
}
void mythread::test()
{
qDebug()<< "线程 "<<(int)QThread::currentThreadId(); //打印线程号
QString str =QString::number((int) QThread::currentThreadId());
emit ID(str); //发送线程ID 到主页面槽函数 打印
}
在主页面打开线程
在主界面 创建新类 并把新的类 moveToThread到QThread中
看下列 代码 带星的 记牢******
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include "mythread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();// 按钮的 槽函数
void GetID(QString ID); // 线程发送信号 主页面接受触发的 槽函数
signals:
void sendsignal();// 按钮发送到 线程的信号
private:
Ui::MainWindow *ui;
QThread workthread; //*********
};
#endif // MAINWINDOW_Hmainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//----------------------------------------------------
mythread *my_thread = new mythread();**********
my_thread->moveToThread(&workthread);//moveToThread 线程 *****************
// 信号和槽
QObject::connect(&workthread, &QThread::finished,
my_thread, &QObject::deleteLater); // 线程结束,自动删除对象********
QObject::connect(this,&MainWindow::sendsignal,
my_thread,&mythread::test);// 发送信号 到线程 槽函数
QObject::connect(my_thread,&mythread::ID,
this,&MainWindow::GetID);
workthread.start(); // 线程 开始 -----------------**********一定要的 *******
//-----------------------------------------------------
}
MainWindow::~MainWindow()
{
delete ui;
workthread.quit();// 结束线程 -----------******一定要的——————————————
workthread.wait();
}
void MainWindow::on_pushButton_clicked()
{
qDebug()<< (int)QThread::currentThreadId();
emit sendsignal();
}
void MainWindow::GetID(QString ID)
{
ui->label->setText(ID);
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}

这篇博客介绍了如何在Qt环境中通过对象继承的方式来实现多线程,并展示了一个简单的程序,该程序开启动一个线程并打印线程ID。文章详细讲解了mythread类的定义,以及如何在主窗口中创建并迁移线程到QThread中。
9181

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



