QObject::connect: No such slot (Qt, C++)

2020-05-07 18:31发布

I can run the program but the button cannot access the send function. I get this hint:

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

Someone knows what's my mistake?

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){
    ...
}

3条回答
Melony?
2楼-- · 2020-05-07 18:42

In fact, you have 2 mistakes in your code:

  1. the SLOT macro takes the type of arguments as parameter not their name, then the code should be : SLOT(send(std::string, std::string)).
  2. You try to connect a SIGNAL which has less argument than the SLOT which is impossible.

In order to avoid all these problems you can use the new signal/slot syntax (if your are using Qt5):

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

I also invite you to use the QString class instead of std::string when working with Qt, it is a lot easier.

查看更多
贼婆χ
3楼-- · 2020-05-07 18:59

That depends on what you want to do:

If emailInput and pwdInput come from widgets, you have to write an intermediate slot that will get the values and call send.

If they are local variables, the easiest is probably to use a lambda.

查看更多
够拽才男人
4楼-- · 2020-05-07 19:01

Should be

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

Macros SIGNAL and SLOT expect method's signature as argument(s).

Additionally, you can connect a signal to a slot of less arity, not the vice versa; here, QObject would not simply know what should be substituted for slot's arguments. You can use the overload of connect that accepts an arbitrary Functor (an anonymous closure, most likely) as slot:

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

Thirdly, were you to use QString instead of std::string, you would not have that heavy copy overhead when passing by value.

查看更多
登录 后发表回答