【问题标题】:Why does adding a function argument cause a SLOT() to be unrecognised?为什么添加函数参数会导致 SLOT() 无法识别?
【发布时间】:2018-09-28 08:04:25
【问题描述】:

我有一堂课如下:

handler.h:

#ifndef HANDLER_H
#define HANDLER_H

#include <QObject>

class handler : public QObject
{
    Q_OBJECT

public:
    explicit handler(QObject *parent = nullptr);
    ~handler();

public slots:
    void returnHandler(int input);
};

#endif // HANDLER_H

handler.cpp:

#include "handler.h"
#include "otherclass.h"

handler::handler(QObject *parent) : QObject(parent)
{

}

handler::~handler()
{

}

void handler::returnHandler(int input)
{
    otherclass *otherclassPointer = otherclass::getInstance();
    otherclassPointer->returnFunction(input);
}

如图所示,这是一个非常简单的类,旨在接收输入并将输入传递给外部类('otherclass')中的函数。在我的主应用程序('main.cpp')中,我创建了一个QThread,并在QThread启动时调用returnHandler槽,如下:

ma​​in.cpp:

QThread* newThread = new QThread();
handler* handlerPointer = new handler();
handlerPointer->moveToThread(newThread);
connect(newThread, SIGNAL(started()), handlerPointer, SLOT(returnHandler(someInput)));
newThread->start();

我遇到的问题是这样的:

  • 我目前收到以下错误:

    QObject::connect: No such slot handler::returnHandler(someInput) in ../app/main.cpp:100

  • 1234563 /p>

为什么添加参数会导致插槽不再被识别?

编辑:在下面的一些非常有用和赞赏的 cmets/answers 之后,我修改了方法如下:

  1. 在处理程序类中创建一个与returnHandler 槽的参数匹配的信号。例如。无效handlerSignal(int)。
  2. 使用handlerSignal() SIGNAL 代替connect() 中的QThread::started() 信号。
  3. QThread 启动后发出handlerSignal()

`

QThread* newThread = new QThread();
handler* handlerPointer = new handler();
handlerPointer->moveToThread(newThread);
connect(handlerPointer, SIGNAL(handlerSignal(int)), handlerPointer, SLOT(returnHandler(int)));
newThread->start();
emit handlerPointer->handlerSignal(someInput);

谢谢!

【问题讨论】:

  • 你必须以这种方式定义连接槽:SLOT(returnHandler(int)。 IE。您需要提供相当插槽的签名。
  • 请注意,startedreturnHandler 的签名与附加参数不匹配...
  • 您可能(如果使用 Qt5)更喜欢新语法:connect(thread, &amp;QThread::started, hp, &amp;Handler::returnHandler);。新语法甚至允许使用 lambda:connect(thread, &amp;Qthread::started, [&amp;hp, someInput]() { /*...*/ });

标签: c++ qt signals-slots


【解决方案1】:

connectstrings 作为要连接的信号和槽的标识。宏 SIGNALSLOT 将它们的参数字符串化(为此使用预处理器功能)。因此,SIGNALSLOT 的参数必须是函数名,括号中带有参数types。您不能对它们进行参数绑定。

如果需要连接零信号,则需要零槽。

【讨论】:

    【解决方案2】:

    两件事:

    1. Qt 期望信号和槽具有相同的参数类型。
    2. 在 SLOT() 中,您必须为参数提供类型,而不是名称。
      SLOT(returnHandler(int))
      而不是
      SLOT(returnHandler(someInput))
      Qt 使用信号和槽的名称和参数列表来识别它们。在你的情况下,Qt 会从“someInput”类型中寻找一个名为“returnHandler”并且只有一个参数的插槽。

    【讨论】:

    • 在这种情况下,信号还必须包含一个 int 参数类型,即 SIGNAL(started(int))?如果我想将(所需类型的)变量传递给槽函数,而不仅仅是类型本身,我的方法是否不正确?
    • 是的,我认为您部分误解了 Qt 提供的信号槽机制。您的插槽将获得的参数是在调用激活插槽的信号时提供的参数。
    • 感谢 NonoxX,我现在理解并解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2014-12-30
    • 2019-08-07
    相关资源
    最近更新 更多