qt使用moveToThread,开启线程。demo模版

发布于:2025-05-01 ⋅ 阅读:(12) ⋅ 点赞:(0)
#ifndef THREAD_H
#define THREAD_H

#include <QObject>

class Thread :public QObject
{
    Q_OBJECT
public:
    Thread();
    ~Thread();
    void Thread_Fun(void);
};

#endif // THREAD_H

#include "outputlogthread.h"
#include <QDebug>
#include <QThread>
Thread::Thread()
{
    qDebug()<<"Thread构造函数ID:"<<QThread::currentThreadId();
}

Thread::~Thread()
{

}

void Thread::Thread_Fun()
{
    qDebug()<<"子线程功能函数ID:"<<QThread::currentThreadId();
}

主线程

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include"outputlogthread.h"

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


signals:
    void ToThread(); // 信号
public:
    QThread *Thread_Test;
    Thread *thread_class;
private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QThread>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Thread_Test = new QThread;
    thread_class = new Thread;
    connect(this,&MainWindow::ToThread,thread_class,&Thread::Thread_Fun);
    thread_class->moveToThread(Thread_Test);
    //下面两个是一样的,都可以调用
    Thread_Test->start();
    // emit ToThread();


}

MainWindow::~MainWindow()
{
    delete ui;
}


网站公告

今日签到

点亮在社区的每一天
去签到