Qt - 多线程中的信号与槽

Qt - 多线程中的信号与槽,第1张

Qt - 多线程中的信号与槽

先看代码和运行效果图,如下:

#ifndef MYOBJECT_H
#define MYOBJECT_H

#include 

class MyObject : public QObject
{
    Q_OBJECT
public:
    explicit MyObject(QObject *parent = 0);
    

protected slots:
    void getStarted();
    void testSlot();
};

#endif // MYOBJECT_H
#include "MyObject.h"
#include 
#include 

MyObject::MyObject(QObject *parent) :
    QObject(parent)
{
}

void MyObject::getStarted()
{
    qDebug() << "void MyObject::getStarted() tid = " << QThread::currentThreadId();
}

void MyObject::testSlot()
{
    qDebug() << "void MyObject::testSlot() tid = " << QThread::currentThreadId();
}

 

#ifndef TESTTHREAD_H
#define TESTTHREAD_H

#include 

class TestThread : public QThread
{
    Q_OBJECT

protected:
    void run();
public:
    explicit TestThread(QObject *parent = 0);
    
signals:
    void testSignal();
protected slots:
    void testSlot();
};

#endif // TESTTHREAD_H

 

#include "TestThread.h"
#include 

TestThread::TestThread(QObject *parent) :
    QThread(parent)
{
    connect(this, SIGNAL(testSignal()), this, SLOT(testSlot()), Qt::QueuedConnection);
}

void TestThread::run()
{
    qDebug() << "void TestThread::run() -- begin tid = " << currentThreadId();

    for(int i=0; i<5; i++)
    {
        qDebug() << "void TestThread::run() i = " << i;

        msleep(800);
    }

    emit testSignal();
    
    exec();

    qDebug() << "void TestThread::run() -- end";
}

void TestThread::testSlot()
{
    qDebug() << "void TestThread::testSlot() tid = " << currentThreadId();
}
#include 
#include 
#include 
#include "TestThread.h"
#include "MyObject.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "main() tid = " << QThread::currentThreadId();

    TestThread t;
    MyObject m;

    QObject::connect(&t, SIGNAL(started()), &m, SLOT(getStarted()), Qt::QueuedConnection);
    QObject::connect(&t, SIGNAL(testSignal()), &m, SLOT(testSlot()), Qt::QueuedConnection);
    
    m.moveToThread(&t);

    t.start();
    
    return a.exec();
}

 运行结果图:

 对象m通过moveToThread函数更改了对象的线程依附性(更改为依附于线程对象t), 而对象t没有更改线程的依附性(依附于主线程),所以t对象中的槽函数是由主函数所调用,对象m中的槽函数是由线程t调用执行的。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5611254.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存