connect
{connect(ui->add, SIGNAL(clicked()),ui->text,SLOT(text.append(line)));}
question I want to add a function that is appended to the lower text window when I enter a string in the upper line window and click Add, but the function does not work.
Asked
Active
Viewed 220 times
0

Farshid616
- 1,404
- 1
- 14
- 26

level 0
- 1
- 1
-
1Concerning your first question: Please, stop using Qt4 styled signal connections. With Qt5 signal connections, you get compile time checks. Btw. you will see how easy such things can be tied together with few lines of code (and using e.g. a lambda). – Scheff's Cat May 18 '21 at 10:23
-
1FYI: [Qt: Signals & Slots](https://doc.qt.io/qt-5/signalsandslots.html) and an example [SO: How to subclass QPushButton so that the signal sends an argument to the slot?](https://stackoverflow.com/a/43015250/7478597) – Scheff's Cat May 18 '21 at 10:28
2 Answers
0
You can connect your button to a lambda slot to do what you want in Qt5 style like this:
connect(ui->add, &QPushButton::clicked, this, [this]() {
ui->text->append(line);
} );

Farshid616
- 1,404
- 1
- 14
- 26
0
I assume your 'ui->add' is the button and 'ui->text' is the QTextEdit? If that's the case, as suggested by Farshid616, you need to use a lambda. Why? two reasons:
- In Qt's Signals & Slots, if you want to pass an argument to the SLOT, you need to return it in the SIGNAL. In your case,
clicked()
doesn't return anything (see function signature here), whileappend(const QString &text)
takes a string (see here). - Lambdas are an easy way to overcome this issue by using
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
, where we use a lambda as the functor (see an example bellow). This is an overloaded connect call (see the signature here).
QObject::connect(your_button, &QPushButton::clicked, [this]() {
your_text_edit->append(your_line_edit->text());
} );
Note: you need to "capture" this
(current object pointer) in the lambda in order to be allowed to access your_text_edit
and your_line_edit
, which are members of this
(i.e. this->your_text_edit
and this->your_line_edit
). The capture of this
is by reference. You can see this more clearly if we write a bit more explicitly the code above:
QObject::connect(this->your_button, &QPushButton::clicked, [this]() {
this->your_text_edit->append(this->your_line_edit->text());
} );

atlas29
- 46
- 4