【问题标题】:QObject::connect: No such slot (Qt, C++)QObject::connect: 没有这样的插槽 (Qt, C++)
【发布时间】:2017-09-27 21:02:38
【问题描述】:

我可以运行程序,但按钮无法访问发送功能。我得到这个提示:

QObject::connect: No such slot Mail::send(emailInput, pwdInput)

有人知道我的错误是什么吗?

mail.h:

#ifndef MAIL_H
#define MAIL_H

#include <QWidget>

namespace Ui {
class Mail;
}

class Mail : public QWidget
{
    Q_OBJECT

public:
    explicit Mail(QWidget *parent = 0);
    ~Mail();

public slots:
    void send(std::string email, std::string pwd);

private:
    Ui::Mail *ui;
};

#endif // MAIL_H

mail.cpp:

Mail::Mail(QWidget *parent) :
    QWidget(parent)
{

    QLineEdit *edt1 = new QLineEdit(this);
    grid->addWidget(edt1, 0, 1, 1, 1);
    std::string emailInput = edt1->text().toStdString();
    ...

    QObject::connect(acc, SIGNAL(clicked()),this, SLOT(send(emailInput, pwdInput)));
}


void Mail::send(std::string email, std::string pwd){
    ...
}

【问题讨论】:

标签: c++ qt connect slot


【解决方案1】:

实际上,您的代码中有 2 个错误:

  1. SLOT 宏将参数的类型作为参数而不是它们的名称,那么代码应该是:SLOT(send(std::string, std::string))
  2. 您尝试连接参数少于 SLOT 的 SIGNAL,这是不可能的。

为了避免所有这些问题,您可以使用新的信号/槽语法(如果您使用的是 Qt5):

QObject::connect(acc, &QLineEdit::clicked, this, &Mail::onClicked);

我还邀请您在使用 Qt 时使用 QString 类而不是 std::string,这样会容易得多。

【讨论】:

    【解决方案2】:

    这取决于你想做什么:

    如果emailInputpwdInput 来自小部件,则必须编写一个中间槽来获取值并调用发送。

    如果它们是局部变量,最简单的可能是使用 lambda。

    【讨论】:

    • 刚刚编辑了帖子。我想将文本保存在 QLineEdit 中,然后使用变量调用 send。
    • 然后您必须编写第一个不带参数并连接到您按钮的单击信号的插槽,并使用实际值调用发送(或者在 lambda 中执行,但它可能很快就会变得混乱^^)
    【解决方案3】:

    应该是

    QObject::connect(acc, SIGNAL(clicked()),this, SLOT(send(std::string, std::string)));
    

    SIGNALSLOT 期望方法的签名作为参数。

    此外,您可以将信号连接到较少数量的插槽,反之亦然;在这里,QObject 不会简单地知道应该用什么来代替 slot 的参数。您可以使用connect 的重载,它接受任意Functor(很可能是匿名闭包)作为插槽:

    QObject::connect(acc, SIGNAL(clicked()), [=](){ send(std::string(), std::string()); });
    

    第三,如果您使用QString 而不是std::string,则在按值传递时不会有那么大的复制开销。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多