Program crashes when i setCentral Widget



  • Can somebody please explain why this simple program crashes on the last line of code

     ui->plainTextEdit->setPlainText(text);
    

    I create a pointer tEdit to an instance of QPlainTextEdit and set it as the central widget using in the constructor.
    Then I get a file using QFileDialog and read the file to the textEditor. If I comment out (setCentralWidget(tEdit)) the program works fine. Can someone please explain why?

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    //    tEdit = new QPlainTextEdit(this);
    //    setCentralWidget(tEdit);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::on_actionNew_triggered()
    {
        QString filename = QFileDialog::getOpenFileName(this, "File Dialog", "C:/Users/Scott/MyFolder");
        QFile file(filename);
        if(!file.open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::warning(this, "Message to User", "File could not open");
        }
    
        QTextStream in(&file);
        QString text = in.readAll();
        qDebug() << text;
        ui->plainTextEdit->setPlainText(text);
        file.close();
    }
    


  • Because when you set a new central widget, the old one (ui->plainTextEdit) gets deleted. either you use tEdit ->setPlainText(text); or leave ui->plainTextEdit as central widget



  • Ok makes a lot of sense, thanks!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.