Solved How to send event to currently focused widget in Qt?
-
Hi,
I am trying to make a custom paste function for the app I am using, if invoked will generate a random number and paste that.
I can easily do this with an extra hotkey which would replace the clipboard and then I would use Ctrl+V to paste. But I want to use a single hotkey to do the same.
I want to use Alt+V to generate random number and paste this. So I thought QApplication.postEvent would be the way to go. But it seems to require the widget to send the event to. How can I find the currently focused widget?
So I can do this:
generate some random number and set clipboard text to this
key = QtGui.QKeyEvent(QtGui.QKeyEvent.KeyPress, QtGui.Qt.Key_V, QtGui.Qt.Key_Control)
QtWidgets.QApplication.postEvent(FIND_CURRENTLY_FOCUSED_WIDGET, key)Because this is a 3rd party app, I don't want to mess with installing event filters, etc. So the above should be the simplest right?
Thanks a lot in advance.
EDIT: I found it:
QtWidgets.QApplication.focusWidget()but still doesn't work for some reason. The name of the method confused me. I was expecting, focusedWidget, coz focus is verb. But still I don't seem to get the key press trigger an event.
-
Thanks I figured it out: https://www.qtcentre.org/threads/69792-QKeyPress-Simulating-key-press
I don't know why qt also requires a string representation on top of all these enums. Doing so it worked.
-
@lachdanan Every QWidget has https://doc.qt.io/qt-5/qwidget.html#focus-prop
You could use this and iterate over all your widgets (https://doc.qt.io/qt-5/qobject.html#children).
A bit cumbersum but should work. -
Thanks I figured it out: https://www.qtcentre.org/threads/69792-QKeyPress-Simulating-key-press
I don't know why qt also requires a string representation on top of all these enums. Doing so it worked.