## minimal code
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import Qt
class Browser(QWebEngineView):
def __init__(self, parent=None):
super(Browser, self).__init__(parent)
self.setHtml(r"""
<div><textarea></textarea></div>
<style>
*{margin:0;}
div {
height: 100%;
position: relative;
background:grey;
}
textarea {
background:red;
height: 50%;
width: 50%;
resize: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
""")
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
central=QtWidgets.QWidget(self)
self.setCentralWidget(central)
layout = QtWidgets.QGridLayout(central)
self.browser = Browser(central)
layout.addWidget(self.browser)
another=QtWidgets.QWidget(central)
layout.addWidget(another)
another.setFocusPolicy(Qt.StrongFocus)
def keyPressEvent(self, e):
print("KEY PRESSED")
return super().keyPressEvent(e)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.setGeometry(300, 50, 800, 600)
window.show()
sys.exit(app.exec_())
Current behavior:
Case 1:
- Click on the white area(a widget).
- Press a key.
KEY PRESSED
is logged into the console.
Case 2:
- Click on the grey area(the webview).
- Press a key.
KEY PRESSED
is logged into the console.
Case 3:
- Click on the red area(the textarea inside the webview).
- Press a key.
- Nothing is logged into the console.
Required behavior
I want all of the cases to log KEY PRESSED
once into the console.
Things I tried
I tried adding an eventFilter
to the MainWindow
but it gives the same outout.
I also tried the solution from this answer by forwarding the key events to MainWindow
but then it logs KEY PRESSED
twice for Case 2.
I am not able to differentiate between the events that was propagated to MainWindow
(Case 2) and those that weren't (Case 3) so that I could've implemented something to ignore the excess function call.