How do I get a reference to the mainwindow via Signal&Slots
-
Use the method sender() available in QObject to get the reference of the sender inside the slot.
If it is any QAction which is calling this slot then change the way you connect to the last slot by.
QAction -> MainWidnow -> Final Slot -
You should not do it at all. Else this class would know details of the main window and if you change the main window you have to update this class. Why do you need access?
Better would be to use signals and slots to communicate between main window and this class (but without passing a reference to the main window). -
You should not do it at all. Else this class would know details of the main window and if you change the main window you have to update this class. Why do you need access?
Better would be to use signals and slots to communicate between main window and this class (but without passing a reference to the main window).Hi, Let me rephrase your sentences for the sake of clarification .
I assume "this class" these words you're referring to a new class , which also means "this class" also known as "seperate class" as I have mentioned in my question .Second thoughts,
you mentioned "Else this class would know details of the main window " in your comment. Actually this is i wanted to do,** retrieve the information from mainWindow and display the information on newWindow.**Third thoughts,
You also mentioned: "Better would be to use signals and slots to communicate between main window and this class (but without passing a reference to the main window)."How do I achieve this ? How do I implement it ? Can you provide me an example ?
Thanks
-
Its all explained here: http://doc.qt.io/qt-5.6/signalsandslots.html
If the instance of the separate class is created in the main window class then you can pass needed information to the constructor of the separate class.
If the information will be available later, then you can emit a signal with all needed data as parameter in main window and connect a slot to this signal in the separate class:// MainWindow ... public: MainWindow() { separateClass = new SeparateClass(this); connect(this, SIGNAL(dataAvailable(QString)), separateClass, SLOT(doSomething(QString))); } signals: // You do emit dataAvailable(data); somethere in MainWindow as soon as new data is available void dataAvailable(const QString &data); private: SeparateClass *separateClass; // SeparateClass public slots: void doSomething(const QString &data);