Here are three easy ways to make your QsciScintilla‐based editor “pass” ESC back to your QDialog so it will close:
- Use a QShortcut in the dialog
- Install an event filter on the QsciScintilla widget
- Subclass QsciScintilla and override keyPressEvent
—
- QShortcut (the simplest)
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QShortcut, QApplication
from PyQt5.QtCore import Qt
from PyQt5.Qsci import QsciScintilla
import sys
class MyDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("ESC Closes Me")
lay = QVBoxLayout(self)
# your QsciScintilla editor
self.editor = QsciScintilla(self)
lay.addWidget(self.editor)
# make sure ESC anywhere in this dialog (and its children)
# triggers reject()
esc = QShortcut(Qt.Key_Escape, self)
esc.setContext(Qt.WidgetWithChildrenShortcut)
esc.activated.connect(self.reject)
if __name__ == "__main__":
app = QApplication(sys.argv)
dlg = MyDialog()
dlg.exec_()
- Event‐filter on the editor
from PyQt5.QtCore import QObject, QEvent, Qt
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QApplication
from PyQt5.Qsci import QsciScintilla
import sys
class EscCatcher(QObject):
def __init__(self, dialog):
super().__init__(dialog)
self.dialog = dialog
def eventFilter(self, obj, ev):
if ev.type() == QEvent.KeyPress and ev.key() == Qt.Key_Escape:
# consume it and close the dialog
self.dialog.reject()
return True
return False # pass all other events along
class MyDialog(QDialog):
def __init__(self):
super().__init__()
lay = QVBoxLayout(self)
self.editor = QsciScintilla(self)
lay.addWidget(self.editor)
# install our filter
self.editor.installEventFilter(EscCatcher(self))
if __name__ == "__main__":
app = QApplication(sys.argv)
dlg = MyDialog()
dlg.exec_()
- Subclass QsciScintilla
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QApplication
from PyQt5.Qsci import QsciScintilla
import sys
class MyScintilla(QsciScintilla):
def keyPressEvent(self, ev):
if ev.key() == Qt.Key_Escape:
# assume parent() is the dialog…
self.parent().reject()
else:
super().keyPressEvent(ev)
class MyDialog(QDialog):
def __init__(self):
super().__init__()
lay = QVBoxLayout(self)
self.editor = MyScintilla(self)
lay.addWidget(self.editor)
if __name__ == "__main__":
app = QApplication(sys.argv)
dlg = MyDialog()
dlg.exec_()
Pick whichever feels cleanest in your code-base. All three approaches will catch the ESC press even when the QsciScintilla widget has focus, and then close (reject) your dialog.