Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Program crashes when trying to change label text from another class.



  • Hi,

    I'm building a simple program, where a push button is clicked, it changes text of label, but the thing is, the program works fine when I write code in MainWindow.cpp , i.e the file where code is autogenerated for ui. But, the program crashes, when I try to call a function from another class, and try to change text from that class.

    The following way works.

    MainWindow.cpp

    void MainWindow::on_pushButton_1_clicked()
    {
       ui->stackedWidget->setCurrentIndex(1);
       ui->myLabel->setText("This works!");
    }
    

    But, when I try to call a function and try to manipulate the label from inside of that function, the program crashes.

    The following way doesn't work.

    void MainWindow::on_pushButton_1_clicked()
    {
        ui->stackedWidget->setCurrentIndex(1);
        gamePlay *play= new gamePlay();
        play.playGame();
    }
    

    Inside another class.

    void gamePlay::playGame() {
        
       ui->myLabel->setText("This does not work!");
    }
    

    The program doesn't crash when I try to call the empty function, but when I try to change text of label, it crashes.

    I have included all MainWindow header files in gamePlay header files, but it still doesn't work. What am I missing? Please let me know.


  • Lifetime Qt Champion

    @johnAdams said in Program crashes when trying to change label text from another class.:

    but when I try to change text of label, it crashes.

    Was ui initialised in gamePlay?


Log in to reply