Search code examples
c++qtqtextedit

Qt program crashes when using insertText


I'm trying to display some information in my Qt program with the QPlainTextEdit, which I included with the Qt Designer. But when i try to display something with

pTextEdit->insertPlainText("text");

my program crashes on execution. When I try to declare the object myself

QTextEdit *txt = new QTextEdit();

it doesn't work either.

The only time it works is when I create the object in the main.cpp. But I need to display the information in my widget not in another window.

Any help is appreciated.

EDIT:

working:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    QTextEdit *txt = new QTextEdit();
    txt->setText("Hello, world!");
    txt->append("Appending some text…");

    txt->show();

    return a.exec();
}

not working (object created by Qt Designer):

MainWindow::MainWindow( QWidget *parent ) :

... initialization list ...

{
    ui->setupUi( this );

    console->setPlainText("text");

    .. other stuff ...
}

Solution

  • Take into consideration that insertPlainText inserts text at current cursor position, so I think you may have problems if cursor is not set (no focus, for example). You may try:

    txt->setPlainText("your text");
    

    Or, if want to append:

    txt->setPlainText(txt->toPlainText() + "appended text");