如何将类中的方法添加到线程中执行?
我不想把"Pup“放到一个继承QThread的独立类中,因为这只是我正在处理的一些遗留代码的抽象。
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();
}发布于 2013-06-22 02:31:44
试试这个:
void Dog::Init()
{
QThread *dogThread = new QThread;
connect(dogThread, SIGNAL(started()), this, SLOT(Pup()), Qt::DirectConnection);
dogThread->start();
}它基本上创建了一个名为dogThread的新QThread,并将它的started()信号连接到您希望在线程内运行的方法(Dog::Pup(),它必须是一个插槽)。
当您使用Qt::QueuedConnection时,该槽将在接收器的线程中执行,但是当您使用Qt::DirectConnection时,该槽将立即被调用,并且因为started()是从dogThread发出的,所以该槽也将从dogThread被调用。您可以在这里找到有关连接类型的更多信息:Qt::ConnectionType。
发布于 2013-06-22 02:18:51
请阅读http://doc.qt.io/qt-5/qthread.html页面中的详细描述
发布于 2013-06-22 04:46:32
如果您希望在另一个线程中运行单个函数,则应该签出QtConcurrent名称空间中的方法。
https://stackoverflow.com/questions/17241422
复制相似问题