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

Call a function from child



  • Hello;
    I would like to call a function from a child form by pressing a button, so I put these codes in my Main window form:

    void MainWindow::Test()
    {
        qDebug()<<"Hello World...";
    }
    

    And I put these codes in my Child form:

    #include "mainwindow.h"
    
    void PicExpand::on_pushButton_clicked()
    {
        MainWindow* myMainwindow = qobject_cast<MainWindow*>(parent());
        if (myMainwindow)
        {
            myMainwindow->Test();
        }
    }
    

    But, it doesn't work !

    Thanks for helping.
    MSD.


  • Moderators

    @MSDQuick said in Call a function from child:

    But, it doesn't work !

    then probably the widget is not a parent of the MainWindow?!


  • Lifetime Qt Champion

    Hi,

    To add to @raven-worx, what you are planning to do is bad design more specifically tight coupling. Why should the child know anything about its parent and furthermore call a function of it ?

    If you want your MainWindow to react to something happening in the child then you should use signals and slots.


Log in to reply