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

Access UI elements from another class with a UI



  • I have two classes with Ui's
    MainWindow and firstStackWidget

    In firstStackWidget I'd like to access the MainWindow's Ui.

    In my firstStackWidget a new menu is shown and I'd like to access that menu from there to connect it to a subclass of firstStackWidget.

    I've already made them friend classes, but that didn't allow me to access the ui elements yet.
    Is there anyone who can help?



  • The Ui's are declared private in the header files, don't change that.. You can delete the friend declarations. I ran into a similar problem calling a function in one QDialog from another. You have to add
    #include " MainWindow.h" at the top of firstStackWidget.cpp. To call functions or slots in MainWindow.h, declare a variable of type MainWindow, then use "dot" to access MainWindow functions. In MainWindow.ui, choose the menu item you wish to access, right-click, go to slot triggered, then in MainWindow.h, change private slots: to public.

    // MainWindow.h
    //private slots:
    public slots:
        void on_actionSomeMenuItem_triggered();
    
    //firstStackWidget.cpp
    #include "MainWindow.h"
    ...
    firstStackWidget::someFunction()
    {
    //...
        MainWindow main;
        main.on_actionSomeMenuItem_triggered();
    }
    

    Do not access the MainWindow UI directly, create a slot for the desired UI menu item-triggered, then call that public slot from the other UI.
    Please let me know if I left anything out.


Log in to reply