Search code examples
c++qtqtcoreqlineeditqt-signals

Qt code does not compile when i try to connect one signal to a slot


I'm new to Qt. I'm trying to implement a really simple calculator program. Just trying to put a button, and when its clicked, i want it to print "Hello, World!" to the next lineEdit. It is working fine when i have only one button, but when I add the second, it doesn't compile. And since I'm coding a calculator, I'm gonna need those buttons.

Here are the errors:

C:\Users\user\Desktop\Calc\build-Calc-Desktop_Qt_5_3_0_MinGW_32bit-Debug\debug\moc_mainwindow.o:-1: In function `ZN10MainWindow18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv':
C:\Users\user\Desktop\Calc\build-Calc-Desktop_Qt_5_3_0_MinGW_32bit-Debug\debug\moc_mainwindow.cpp:75: error: undefined reference to `MainWindow::on_pushButton_clicked()'
C:\Users\user\Desktop\Calc\build-Calc-Desktop_Qt_5_3_0_MinGW_32bit-Debug\debug\moc_mainwindow.cpp:76: error: undefined reference to `MainWindow::on_pushButton_2_clicked()'

here's the MainWindow method:

void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        MainWindow *_t = static_cast<MainWindow *>(_o);
        switch (_id) {
        case 0: _t->on_pushButton_clicked(); break;
        case 1: _t->on_pushButton_2_clicked(); break;
        case 2: _t->on_pushButton_11_clicked(); break;
        default: ;
        }
    }
    Q_UNUSED(_a);
}

and here's how I make the connection:

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


// this is the problematic part
void MainWindow::on_pushButton_11_clicked()
{
    ui->lineEdit->setText("Hello, World!");
}

Does anyone know how to fix this? Thank you for your time.


Solution

  • // this is the problematic part

    void MainWindow::on_pushButton_11_clicked()

    Indeed.

    You are missing out the implementation of the following two methods:

    MainWindow::on_pushButton_clicked()
    {
        ui->lineEdit->setText("Hello, World 2!");
    }
    

    and

    MainWindow::on_pushButton_2_clicked()
    {
        ui->lineEdit->setText("Hello, World 3!");
    }
    

    So, it seems you have three slots eventually instead of two. You will need to implement the others as per your desire. Note that the texts are above just placeholders for whatever actions you are planning to do therein.