1

I want to connect custom slot which takes one int argument to clicked() signal emited by different widget. Here's the sample code:

.h file:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void setLayoutNow();
    void changeLabelText(int nr); //slot I'm talking about
private:
    Ui::MainWindow *ui;
    QLabel *label;
    QPushButton *button1, *button2;
    QVBoxLayout *mainLayout;
};

.cpp file:

void MainWindow::setLayoutNow()
{
    label = new QLabel("LABEL");
    button1 = new QPushButton("WRITE 1");
    button2 = new QPushButton("WRITE 2");

    mainLayout = new QVBoxLayout(ui->centralwidget);
    mainLayout -> insertWidget(0, label, 3);
    mainLayout -> insertWidget(1, button1, 1);
    mainLayout -> insertWidget(2, button2, 1);

    connect(button1, SIGNAL(clicked()), this, SLOT(changeLabelText(1)));
    connect(button2, SIGNAL(clicked()), this, SLOT(changeLabelText(2)));
}

void MainWindow::changeLabelText(int nr)
{
    if (nr == 1)
        label->setText("1");
    if (nr == 2)
        label->setText("2");
}

When I start my app I receive a message qt.core.qobject.connect: QObject::connect: No such slot MainWindow::changeLabelText(1). How am I supposed to connect clicked signal with this slot? What causes the problem?

I read this question which points how qt requires matching argument types but my app gives me different error than Incompatible sender/receiver arguments.

I also want to point out that when I connected functions with no arguments, no problem like that occured.

  • 1
    "***my app gives me different error than `Incompatible sender/receiver arguments`***", that's because you're making another mistake by passing a value to your slot in `connect`, if you use this: `SLOT(changeLabelText(int))`, you will get that error. [Qt 4.8 Signals & Slots](https://doc.qt.io/archives/qt-4.8/signalsandslots.html) – Abderrahmene Rayene Mihoub Jul 06 '23 at 12:49

1 Answers1

4

Do not use the SIGNAL/SLOT macros in 2023. The native connection method raises errors at compile-time and allows you to use lambdas to do whatever you want.

Concretely:

connect(button1, &QPushButton::clicked, this, [this]() { changeLabelText(1); });
connect(button2, &QPushButton::clicked, this, [this]() { changeLabelText(2); });

As an added bonus, your changeLabelText no longer needs to be a slot, it can be a regular method.

Botje
  • 26,269
  • 3
  • 31
  • 41
  • 2
    *"As an added bonus, your `changeLabelText` no longer needs to be a slot"*. It can even be removed, and just use its body: i.e `label->setText("1");`. – Jarod42 Jul 06 '23 at 12:43