Access Action declared in main.py from mainwindow.py
-
I have a main.py that houses the standard declarations and calls to setup up a QApplication, app and window. Within this I am also constructing a QSystemTrayIcon which works. Currently I have "Show" and "Quit", but I would like to toggle the "Show" to "Hide" and back to "Show" as I show and hide the mainwindow.
Next I have a mainwindow.py. In here I have overridden the showEvent and hideEvent . That also works.
Now I would like to use these to toggle the System Tray Menu for the "Show" and "Hide" entries / actions appropriately.My question is how do I access the actions constructed in main.py from mainwindow.py which will allow me to set the relevant actions visible or not.
Thanks as always,
jBdef main() -> None: # sourcery skip: extract-method, remove-pass-body, remove-redundant-pass, swap-if-else-branches """ Start the Main Function to get us going. """ try: app = QApplication(sys.argv) window = MainWindow(app) ... tray_menu = QMenu() action1 = QAction("Show") action1.triggered.connect(window.showNormal) # type: ignore action1.triggered.connect(window.activateWindow) action1.triggered.connect(window.raise_) action1.setIcon(QIcon(u":buttons/buttons/glassRound/glassButtonShow.png")) tray_menu.addAction(action1) action2 = QAction("Hide") action2.triggered.connect(window.hide) action2.setIcon(QIcon(u":buttons/buttons/glassRound/glassButtonHide.png")) action2.setVisible(False) tray_menu.addAction(action2)
class MainWindow(QMainWindow, Ui_MainWindow): """ The MainWindow Class. """ def __init__(self, app) -> None: super().__init__() self.setupUi(self) # type: ignore self.app = app # declare an app member ... def hideEvent(self, event: QHideEvent) -> None: print("Hide Event Triggered") >>> HERE IS WHERE I WANT TO ACCESS THE ACTIONS FROM main.py <<< return super().hideEvent(event) def showEvent(self, event: QShowEvent) -> None: print("Show Event Triggered") >>> HERE IS WHERE I WANT TO ACCESS THE ACTIONS FROM main.py <<< return super().showEvent(event) ```
-
@britesc
If you choose to declare/define them inmain()
you will need to pass them as parameters toMainWindow
, or passtray_menu
and read its actions, or via a setter exported from there, or some equivalent.Whether the actions might be better declared in
MainWindow
is a different matter. Probably depends how/where you use them. -
Hi,
Since these actions are there to manipulate the main window and updated by it, I would recommend that you create them in your MainWindow class and then retrieve them from it to be added to your QSystemTray object.