[Interest] Receive key presses when hovering over a specific widget

Murphy, Sean smurphy at walbro.com
Thu Jul 11 22:03:16 CEST 2019


> AFAIK, the easiest way to trap keyPress/keyRelease irrespective of which
> widget has the focus is to install an event filter on the QApplication
> instance.  Use the mouseEnter/Leave events of the thumbnails to set/clear a
> currentThumbnail, and then in eventFilter only act on the 'm' keyPress if the
> currentThumbnail has been set, and return false from the filter, otherwise
> return true so that the 'm' will go to the edit box or whatever.

I had pretty good luck with the following setup (example attached).
In the thumbnail class I override these functions and added the described behavior
in addition to letting the base class handle the rest of the behavior:
 - enterEvent() - in here I call grabKeyboard()
 - leaveEvent() - in here I call releaseKeyboard(), as well as emit a "hide popup" signal
 - keyPressEvent() - in here I emit a "show popup" signal only if the pressed key matches 
   my target (in this case the 'm' key)
 - keyReleaseEvent() - in here I emit a "hide popup" signal only if the released key matches 
   my target (in this case the 'm' key)

Then in the parent container class, I have show/hide popup slots connected to the 
show/hide signals of each thumbnail object. By doing it this way I keep the 
MainWindow class, QApplication class, etc. out of the loop since they don't 
really have anything to do with the functionality I'm looking for, so I like the 
way it's working so far - it better encapsulates the functionality within the classes that
care about it.

The attached example creates 3 thumbnail widgets each with a different 
background color, as well as a line edit that has focus to start. Pressing the 
'm' key (or any other key) will type in the line edit UNLESS you move the 
cursor over any one of the 3 thumbnails. In which case, pressing the 'm' 
key will popup a new widget that has the same background color as the 
thumbnail you were hovering over, so I think it's behaving the way I want, I just 
need to roll it all into my actual application.

Sean


This message has been scanned for malware by Forcepoint. www.forcepoint.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: widgetMouseoverKeyPress.zip
Type: application/x-zip-compressed
Size: 4581 bytes
Desc: widgetMouseoverKeyPress.zip
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20190711/65690434/attachment.bin>


More information about the Interest mailing list