Search code examples
qtqtexteditqlineedit

Qt: Synchronous QLineEdit and QTextEdit


I have a Qt project that has a UI with many QLineEdits and one QTextEdit. I just want to merge the input of the individual QLineEdits into the QTextEdit. For example: when someone types in the first QLineEdit, I want the QTextEdit's first line to match. If someone types something in the 13th QLineEdit, the QTextEdit's 13th line should update to match. If a line editor is empty, the text editor's same lines will be empty too. Thanks.


Solution

  • you can have a UpdateTextEdit slot in your window/dialog's class, like this:

    void ExampleDialog::UpdateTextEdit(){
        QString str= ui->lineEdit1->text();
        str+= "\n";
        str+= ui->lineEdit2->text();
        str+= "\n";
        str+= ui->lineEdit3->text();
        str+= "\n";
        ...
        //add text from all your line edits
        ...
    
        ui->textEdit->setPlainText(str);
    }
    

    and in the dialog/window's constructor, connect textChanged signal from all your QLineEdits to the UpdateTextEdit() slot, like this:

    ExampleDialog::ExampleDialog(QWidget* parent):QDialog(parent),...{
        ...
        ...
        connect(ui->lineEdit1, SIGNAL(textChanged(const QString &)), this, SLOT(UpdateTextEdit()));
        connect(ui->lineEdit2, SIGNAL(textChanged(const QString &)), this, SLOT(UpdateTextEdit()));
        connect(ui->lineEdit3, SIGNAL(textChanged(const QString &)), this, SLOT(UpdateTextEdit()));
        ...
    }