Qt中的线程与信号槽

小实践

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
// #pragma once
#include 
#include"zthread.h"

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class ZThread;

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButton_clicked();
    void onEmitSignalUpdate(int num);

private:
    Ui::MainWindow *ui;
    ZThread* m_pThtread;
};
#endif // MAINWINDOW_H

zthread.h

// #pragma once
#ifndef ZTHREAD_H
#define ZTHREAD_H
#include
#include
#include

// QObject
class ZThread : public QThread
{
    Q_OBJECT
public:
    explicit ZThread(QObject *parent = nullptr);
    ~ZThread();

    void stopthreadrunning();

signals:
    void updateThreadsignal(int num);

protected:
    void run();

private:
    bool m_bRunning; //控制多线程运行。b是布尔类型
    int m_ncount; //n是number类型
};

#endif // ZTHREAD_H

main.cpp

#include "mainwindow.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
// #include "zthread.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_pThtread=new ZThread();
    m_pThtread->start();
    connect(m_pThtread,&ZThread::updateThreadsignal,this,&MainWindow::onEmitSignalUpdate);
    // connect(m_pThtread,SIGNAL(updateThreadsignal(int)),this,SLOT(onEmitsignalupdate(int))); //这样的写法也可以
}

MainWindow::~MainWindow()
{
    if(m_pThtread!=nullptr)
    {
        m_pThtread->stopthreadrunning();
        m_pThtread->quit();
        m_pThtread->wait();
        m_pThtread->deleteLater();
    }

    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    m_pThtread->stopthreadrunning();
}



void MainWindow::onEmitSignalUpdate(int num)
{
    qDebug()<<"==========Thread Signal Update"<

zthread.cpp

#include "zthread.h"

ZThread::ZThread(QObject *parent)
    : QThread{parent},m_bRunning(true),m_ncount(0)
{

}

ZThread::~ZThread()
{

}

void ZThread::run() //The threaded code runs in this
{
    while(m_bRunning) //The code that all threads run on is written here
    {

        // qDebug()<<"T is running......"<

界面:

Qt中的线程与信号槽_第1张图片

运行结果:

Qt中的线程与信号槽_第2张图片

心得

我好像明白了点,我确实语法错了。之前关联信号与槽的时候,明明是不同的两个类,我却在connect前边加上了一个类域,这是其一;信号函数没有函数体定义,不能在.cpp文件中实现,但是我却实现了,还加了类域

没想到  重定义  三个字放到信号signals这里是这样的情况,我粗略地以为只是函数、变量对象等的“重定义、”

 connect(m_pThtread,&ZThread::updateThreadsignal,this,&MainWindow::onEmitSignalUpdate);  函数指针的写法也可以了

注意不要犯错:

Qt中的线程与信号槽_第3张图片

你可能感兴趣的:(Qt音视频开发,qt,开发语言)