Reading text from textEdit

  • Hi,
    I'd like to read the text from this textEdit and store it in a QString:

    QTextEdit *descr_TextEdit = new QTextEdit;
            descr_TextEdit->setFixedWidth (400);
            descr_TextEdit->setFixedHeight (50);
           description = descr_TextEdit->toPlainText ();
            qDebug() << "Description: " << description;

    This doesn't generate any error messages, but the QString description is empty. Please help me to find a better solution. Thank you.

  • Between the first line and last line of your code there is no opportunity for a user to manipulate the text in the QTextEdit. Since you have not set that text it is the default empty editor.

    At the very least the QTextEdit needs to be shown to the user directly (QWidget::show()) or indirectly through inclusion in a larger UI. The first three lines would usually be in the constructor of the class representing a UI, and the other lines would be elsewhere in the program, often a slot.

  • @ChrisW67
    I did what you suggested:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
    	QTextEdit *textEdit = new QTextEdit(thi);
    	textEdit->setFixedWidth (400);
        textEdit->setFixedHeight (50);
        QString description;
        description = textEdit->toPlainText ();
     	textEdit->show ();
    	qDebug() << "Description: " << description;
        delete ui;

    I still have the same problem: still don't know how to capture the text in textedit and transfer it to description. Thank you for your help.

  • Hi, ChrisW67

    That's pretty much normal. You haven't written anything in your QTextEdit between its creation and the moment at which you call QTextEdit::toPlainText; that's why the QString instance "description" is empty. You should wait that the QTextEdit gets filled with some text before calling QTextEdit::toPlainText and showing this, for instance with qDebug().

    I hope that it will help you.

    Have a nice day.

  • @OwonaVivienD
    How can I "wait"?

  • You should write a separate method/slot that performs the whole text "capture'n'show" and that will be triggered by an element of you choice. For example, this element can be a QTimer and its signal QTimer::timeout or a QPushButton and its signal QPushButton::pressed; you just have to do a brainstorming with your imagination. ;)

  • @OwonaVivienD
    Thank you. I think I will go with a QPushButton.

Log in to reply