qtclassobjectslotmainwindow

Qt - mainwindow class object in another class doesn't work well


void MyAnotherClass::mySlot(){
MainWindow window;
window.myFunction();}

void MainWindow::myFunction(){

qDebug() << "THIS qDebug works well but ui do NOT";

ui->textEdit->setText("Why i do not working?");
}

Why qDebug in this situation works fine, but ui->... doesn't? How to fix it?

EDIT: Solution: `QPlainTextEdit *pointer; MainWindow constructor{ pointer=ui->qPlainTextEdit;}

Some Another's class method{ pointer->appendPlainText("It works"); }`


Solution

  • You create new instance of MainWindow class inside MyAnotherClass::mySlot(). When this slots ends this instance is deleted. So you can't see any changes.

    void MyAnotherClass::mySlot() {
        MainWindow window;  //new instance created
        window.myFunction();
    } //here this instance deleted
    

    Instead of this you should have pointer to your main window somewhere inside your MyAnotherClass:

    MyAnotherClass
    {
         .......   
        private slots:
            void mySlot();
    
        private:
            MainWindow* _mainWindow;
          ...............
    };
    

    and then you can do somethins like this:

    void MyAnotherClass::mySlot() {
        _mainWindow->myFunction();
    }
    

    Of course you should somehow init this pointer before you can use it.