Search code examples
c++qtqt5slots

Error when adding buttons, No such slot exists even though it is there


This is the full error i am getting, I do have the moc file in my build folder I am trying to debug and this message apears

Debugging starts
    QObject::connect: No such slot MainWindow::numberClicked(QString buttonInput) in ..\calculator\mainwindow.cpp:14
    QObject::connect:  (sender name:   'pushButtonNr0')
    QObject::connect:  (receiver name: 'MainWindow')

This is my header file, i do have Q_Object macro like some others suggest

    class MainWindow : public QMainWindow {
        Q_OBJECT

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

    private slots:

        void numberClicked(QString buttonInput);

This is my cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    _ui(new Ui::MainWindow) {
    _ui->setupUi(this);

    _inputSwitchDen = true;

    connect(_ui->pushButtonNr0, SIGNAL(clicked()), this, SLOT(numberClicked(QString buttonInput)));

and this is the function

void MainWindow::numberClicked(QString buttonInput = "") {
    QPushButton *clickedButton = qobject_cast<QPushButton *> (sender());
    if (buttonInput == "") {
    buttonInput = clickedButton->text();
    }


    _ui->labelMessage->setText("");


    if (_inputSwitchDen) {
    if (_ui->lineDen->text() == "1")
        _ui->lineDen->setText(buttonInput);
    else {
        _ui->lineDen->setText(_ui->lineDen->text() + buttonInput);
    }
    } else {
    if (_ui->lineNum->text() == "0") {
        _ui->lineNum->setText(buttonInput);

    } else {
        _ui->lineNum->setText(_ui->lineNum->text() + buttonInput);
    }
    }

Thanks for reading


Solution

  • You should make use of the new signal/slot syntax.

    If you really can't change the declaration of MainWindow::numberClicked (although overloading it would be the obvious solution) then you can probably just use a lambda (untested)...

    connect(_ui->pushButtonNr0, &QPushButton::clicked, this,
            [this]()
            {
              numberClicked();
            });
    

    Note, also, that when using the new syntax there is no need to declare slots explicitly -- they're just normal functions.