0

I have some trouble understanding how signal and slots work. I have an input and a button, I want a value to be written on the input field when I click the button. Please show me how it should be done.

#include <QApplication>
#include <QHBoxLayout>
#include <QSlider>
#include <QSpinBox>
#include <QLineEdit>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    // Create main window.
    QWidget *window = new QWidget;
    window->setWindowTitle("Enter your age");
    window->setFixedSize(500,500);

    QLineEdit *value1= new QLineEdit;
    value1->show();

    QPushButton *button1(window)= new QPushButton;
    button1->setText("click");
    button1->show();
    button1->move(300,0);

    QObject::connect(button1,SIGNAL(clicked()),value1,SLOT(setText(2)));


    // Create layout to put widgets in place.
    QHBoxLayout *layout = new QHBoxLayout;
    //layout->addWidget(value1);
    //layout->addWidget(button1);
    // Put layout in main window.
    window->setLayout(layout);
    window->show();
    return app.exec();
}
m7913d
  • 10,244
  • 7
  • 28
  • 56
Barbell
  • 194
  • 1
  • 6
  • 19

1 Answers1

2

This doesn't work because you don't set the function parameters of a slot when connecting, but the parameters will be provided when the signal is emitted.

The clicked() signal doesn't provide a QString, so there's nothing to pass to the function setText(const QString &).

What you can do is define another function that acts as an intermediate step. The button click will connect to your function, which will determine what to set the line text to. This can be done in a so-called lambda expression, as per the docs here.

Example

QObject::connect(button1, &QPushButton::clicked, [=] {
        value1->setText("2");
    });

This should work in your code and you also need to change one line to

QPushButton *button1= new QPushButton(window);
demonplus
  • 5,613
  • 12
  • 49
  • 68
Jay
  • 636
  • 6
  • 19