[PyQt] Handling Windows messages

Claessen, Matt - [Avantes] MattC at avantes.com
Wed Apr 22 11:31:08 BST 2015


Hi,

Using PyQt5 on Windows.
I could use some help with my sample application, which must 
respond to Windows messages being sent to it from our device's DLL.
The messages are sent to the WinId() of the QMainWindow, and I 
have confirmed this with Microsoft's Spy++ utility.

I have followed the PyQt documentation and what I could find on the 
internet to come up with:

class WinEventFilter(QAbstractNativeEventFilter):
    def __init__(self, my_windows_message):
        QAbstractNativeEventFilter.__init__(self)
        self.my_windows_message = my_windows_message
    def nativeEventFilter(self, eventType, message):
        if eventType == "windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(message.__int__())
            if msg.message == self.my_windows_message:
                print("Message Received!")
                # handle_newdata() slot is hard to call, 
                # cannot use signal, does not derive from QObject
        return False, 0

and the filter is installed in main() with:


def main():
    app = application(sys.argv)
    app.lastWindowClosed.connect(app.quit)
    app.setApplicationName("PyQt5 simple demo")
    win_event_filter = WinEventFilter(0x8001)
    app.installNativeEventFilter(win_event_filter)
    form = MainWindow()
    form.show()
    app.exec_()

This works, but I now have two problems:

1) How can I propagate the event to the rest of my program?
In the C++ version of Qt, you can let the QApplication inherit
from QAbstractNativeEventFilter as well, and then you can define
a local signal. Unfortunately, that is not allowed in PyQt.
Defining a pyqtSignal() in the WinEventFilter class is also not 
allowed, as it does not derive from QObject.
So how do you use a Windows Event in the rest of your application?
I have seen people override the Windows message handler in their 
program. Surely that is not necessary?

2) For some reason, the above filter fires twice for each incoming
Windows message. I have noticed similar behaviour in PyQt before.
If you define the callbacks for buttons with the on_Button_clicked()
notation you will get two signals if you explicitly connect the
signal to the slot as well. If you then leave out the @pyqtSlot() 
decorator, you will even get three signals per button click.

Regards, Matt



More information about the PyQt mailing list