【问题标题】:Qt: Using signals and slots between two child threadsQt:在两个子线程之间使用信号和槽
【发布时间】:2013-08-05 10:59:43
【问题描述】:

我是 Qt 和 C++ 的新手,我正在尝试制作一个运行两个子线程 threadA 和 threadB 的程序。两个线程都是在 main.cpp 中创建的,如下所示:

ThreadA threadA;
threadA.start();
ThreadB threadB;
threadB.start();

这两个线程然后独立运行。 我需要使线程A 能够调用线程B 中的方法,在进程中将数据作为参数传递。我尝试使用信号和插槽,将其添加到我的 main.cpp:

QThread::connect(&threadA, SIGNAL(mySignal(uint)),
    &threadB, SLOT(mySlot(uint)));

其中 threadA::mySignal(uint) 用于:

//a.h
signals:
  void mySignal(unsigned int blah);
//a.cpp
  emit mySignal(42);

而threadB::mySlot(uint) 在b:

//b.h
public slots:
    void mySlot(unsigned int fluff);
//b.cpp
void threadB::mySlot(unsigned int fluff)
{ doStuff(fluff); ... }

程序编译并成功运行,但我在调试日志中收到来自 QObject 的消息:

QObject::connect: No such slot QThread::mySlot(uint) in ../Project/main.cpp:42

意味着编译器正在 QThread 中查找 mySlot 而不是 threadB。 谁能告诉我这里哪里出错了?任何帮助将不胜感激,如果需要,我可以提供更多详细信息。

【问题讨论】:

  • 如果我错了,请纠正我,但QThread 没有mySlot,由于某种原因,连接语句引用QThread 而不是您自己的派生类。
  • 是的;这就是问题所在,它在 QThread 而不是 threadB 中寻找插槽

标签: c++ multithreading qt


【解决方案1】:

首先是你提到的错误

程序编译并成功运行,但我收到一条消息 我的调试日志中的 QObject:

QObject::connect: No such slot QThread::mySlot(uint) in ../Project/main.cpp:42

您正在使用 mySlot 并已定义 MySlot 请参考您的代码

你写过

QThread::connect(&threadA, SIGNAL(mySignal(uint)), &threadB, SLOT(mySlot(uint)));

并定义

//b.h

public slots:
    void MySlot(unsigned int fluff);

【讨论】:

  • 对不起,这是在 SA 上编写代码时的拼写错误,不在我的实际代码中。现在编辑它。
  • @user2652805 请发布工作示例,这样很容易解决您的问题。因为当我们发布一半没有意义的代码时。请阅读sscce.org
【解决方案2】:

您可能在threadb.h(也可能是threada.h)中缺少Q_OBJECT 宏。

class ThreadB : public QObject 
{
   Q_OBJECT 
...

来自文档: All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.

我还假设您已将QThread 子类化。你应该知道QThread是用来管理线程的,不是用来处理数据的。您应该改为将QObject 子类化。 Read this 了解更多信息。

【讨论】:

  • 你说得对,我将 QThread 子类化了。我已将其更改为 QObject,并在 threadb.h 中添加了 Q_OBJECT,但现在出现两个构建错误:/home/x/Test/threadb.h:9: error: undefined reference to 'vtable for threadb',在函数 ~threadbthreadb 中。
  • @user2652805 您是否尝试运行 qmake 并重建项目?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多