[QGIS-Developer] How can I connect to events in a QGIS main window from a Python plugin - or: How can I trigger a function once the main window has actually been displayed?

Sebastian M. Ernst ernst at pleiszenburg.de
Sat Aug 17 02:25:59 PDT 2019


Hi all,

in a QGIS Python plugin, I want to run a function (a single time) when
the QGIS main window has actually been displayed / fully loaded.
`initGui` appears to run "long" before the main window is actually being
displayed and ready. My only viable idea so far has been to attach an
event filter to the main window object. The problem is that it does not
get triggered at all (for any type of event).

I attached a minimal, (not) working example below this email.

How can I either make my example work OR how else can I trigger code
based on the QGIS main window having been fully loaded / displayed?

QGIS 3.6 and 3.8 on openSUSE Linux.

Full disclosure, I also posted a related question on SO:
https://stackoverflow.com/q/57534440/1672565

Best regards,
Sebastian



```python

class something:

    def __init__(self, iface):

        self.mainwindow_obj = iface.mainWindow()

    def initGui(self):

        self.wait_for_mainwindow = True
        delay_on_load(self.my_func, self.mainwindow_obj)

    def my_func(self):
        "MUST ONLY RUN WHEN mainwindow_obj HAS BEEN FULLY DISPLAYED"

        if not self.wait_for_mainwindow:
            return
        self.wait_for_mainwindow = False

        # do something useful NOW ...

def delay_on_load(func, qt_widget):

    from PyQt5.QtCore import QObject, QEvent
    from PyQt5.QtWidgets import QMessageBox

    QMessageBox.warning(None, 'TEST', 'Installing filter ...')

    def wrapper():
        qt_widget.removeEventFilter(filter_obj)
        func()

    class filter_class(QObject):
        def eventFilter(self, obj, event):
            QMessageBox.warning(None, 'TEST', 'Got event type "%s"' %
str(event.type()))
            if event.type() == QEvent.Polish: # and obj is qt_widget:
                wrapper()
                return True
            return QObject.eventFilter(obj, event)

    filter_obj = filter_class()
    qt_widget.installEventFilter(filter_obj)

    QMessageBox.warning(None, 'TEST', '... install done.')

```


More information about the QGIS-Developer mailing list