假设我在GUI界面中进行了文本编辑,并且按了一个像 a 这样的键,那么我就不应该得到一个' a'写在我的文字编辑上。
我可以将自己的功能添加到按键事件中,但我不能阻止它执行默认机制。
请帮帮我。
答案 0 :(得分:2)
您可以阻止特定密钥的默认keyPressEvent
行为,如下所示:
class CodeEditor(QtWidgets.QPlainTextEdit):
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_A:
# do nothing
event.accept()
else:
# do the default
super().keyPressEvent(event)
答案 1 :(得分:1)
您可以安装eventFilter并阻止传输密钥。
import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit
from PyQt5.QtCore import QObject, Qt, QEvent
class Helper(QObject):
def disable_key(self, w, key):
self.m_w = w
self.m_w.installEventFilter(self)
self.m_key = key
def eventFilter(self, obj, event):
if obj == self.m_w and event.type() == QEvent.KeyPress:
if event.key() == self.m_key:
return True
return QObject.eventFilter(self, obj, event)
if __name__ == '__main__':
app = QApplication(sys.argv)
helper = Helper()
view = QPlainTextEdit()
helper.disable_key(view, Qt.Key_A)
view.show()
sys.exit(app.exec_())
或通过信件:
import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit
from PyQt5.QtCore import QObject, Qt, QEvent
class Helper(QObject):
def disable_key(self, w, letter):
self.m_w = w
self.m_w.installEventFilter(self)
self.m_letter = letter
def eventFilter(self, obj, event):
if obj == self.m_w and event.type() == QEvent.KeyPress:
if event.text() == self.m_letter:
return True
return QObject.eventFilter(self, obj, event)
if __name__ == '__main__':
app = QApplication(sys.argv)
helper = Helper()
view = QPlainTextEdit()
helper.disable_key(view, "a")
view.show()
sys.exit(app.exec_())