Sebasthian Ogalde
Sebasthian Ogalde

Reputation: 517

How to access QMainWindow from a QWidget which parent is not QMainWindow

I am programming a GUI with Qt Creator (Qt5.10) under OSX. I have a QMainWindow for the main app's window. Inside this I have a QTab widget, in which I have entire widget (let's call it CaptureTabWidget which contains some additional widgets AND a QFrame (the parent of this QFrame is the QTab). In this last widget I will be drawing some stuff. The point is that I would like to write in the statusBar of the QMainWindow some values related to the position of the mouse in that QFrame, but I do not have any idea about how to access the main window from a method inside the CaptureTabWidget which contains the QFrame.

The whole picture goes like this:

                 X
+-----------+  XXX
|MainWindow | XXXXXXXXX
+-----+-----+  XXX    XXXXXX
      |          X         XXX
+-----v------------+          XX
|QTabWidget        |           XX
|No parent         |            XX
+-----+------------+             XX
      |                           X
+-----v-------------+          ?? X
|CaptureTabQWidget  |             X
|Parent:QTabWidget  |             X
+-----+-------------+            X
      |                         X
+-----v-------------+         XX
|QFrame             |    XXXXXX
|Parent:CaptureTab  | XXX
+-------------------+

I have tried modifying the CaptureTabWidget's constructor in order to receive a QMainWindow* which points to the main window, but it seems Qt Creator doesn't allow custom constructors when promoting widgets in the Designer. I am wondering what is the right way to do this.

Upvotes: 2

Views: 2259

Answers (1)

Mike
Mike

Reputation: 8355

If you just aim to write to the statusBar of the parent QMainWindow, you can post a QStatusTipEvent to any child of your QMainWindow, and the event will keep propagating to the parent QWidgets until it reaches the main window where it gets handled by by changing the content in the status bar. In other words, something like this in your QFrame does the job:

QCoreApplication::postEvent(this, new QStatusTipEvent("your tip"));
//                          ^^^^
//                          assuming this is a pointer to your QFrame object

As a side note, this is the same way views in Qt (QTableView, QTreeView, QListView, ...) are able to change status tips (when their models provide a custom value for the role Qt::StatusTipRole) while they might be buried deep down in the QObject tree...


For purposes other than just writing to the statusBar of a parent QMainWindow, I would try to generalize the above approach by having a custom QEvent (i.e. one that has a value between QEvent::User and QEvent::MaxUser) and handle that event in my QMainWindow subclass appropriately. I find this way much cleaner and more maintainable than other solutions that depend on global variables/singletons (that keep track of your supposedly one QMainWindow instance).

Upvotes: 4

Related Questions