想把一个方法放到一个QThread中 [英] Want to put a method into a QThread

查看:43
本文介绍了想把一个方法放到一个QThread中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将类内的方法添加到线程中执行?

How to add a method within the class to a thread to execute?

我不想将Pup"放入继承 QThread 的单独类中,因为这只是我正在处理的一些遗留代码的抽象.

I do not want to put "Pup" into a seperate class that inherits QThread as this is just an abstraction of some Legacy code I am working on.

void Dog::Pup()
{
     printf("pup");
}

void Dog::Init()
{
     QThread *dogThread = new QThread();
     Pup->moveToThread(dogThread); //this is all wrong
     Pup->connect(dogThread, ?, Pup, SLOT(Pup), ?)
     dogThread.start();
}

推荐答案

试试这个:

void Dog::Init()
{
     QThread *dogThread = new QThread;
     connect(dogThread, SIGNAL(started()), this, SLOT(Pup()), Qt::DirectConnection);
     dogThread->start();
}

它基本上创建了一个名为 dogThread 的新 QThread 并将它的 started() 信号连接到要在线程内运行的方法(Dog::Pup() 必须是一个槽).

It basically creates a new QThread named dogThread and connects it's started() signal to the method you want to run inside the thread (Dog::Pup() which must be a slot).

当您使用 Qt::QueuedConnection 时,槽将在接收者的线程中执行,但是当您使用 Qt::DirectConnection 时,槽将立即被调用,并且因为 started() 是从 dogThread 发出的,所以槽也将从 dogThread 调用.您可以在此处找到有关连接类型的更多信息:Qt::ConnectionType.

When you use a Qt::QueuedConnection the slot would be executed in the receiver's thread, but when you use Qt::DirectConnection the slot will be invoked immediately, and because started() is emitted from the dogThread, the slot will also be called from the dogThread. You find more information about the connection types here: Qt::ConnectionType.

这篇关于想把一个方法放到一个QThread中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆