Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Program crashes when i setCentral Widget

Program crashes when i setCentral Widget

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 757 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    ssoffel
    wrote on last edited by VRonin
    #1

    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();
    }
    
    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by
      #2

      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

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      1 Reply Last reply
      2
      • S Offline
        S Offline
        ssoffel
        wrote on last edited by
        #3

        Ok makes a lot of sense, thanks!

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved