简体   繁体   中英

C++ QT5 TextEdit append

  1. connect

    {connect(ui->add, SIGNAL(clicked()),ui->text,SLOT(text.append(line)));}

  2. 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.

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);
} );

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:

  1. 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 ), while append(const QString &text) takes a string ( see here ).
  2. 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 (ie 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());
} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM