实现QTextEdit输入内容的过滤有两种方法,一种是通过重载QTextEdit的keyPressEvent()方法实现,简单举个例子实现只能在QTextEdit中只能输入16进制的数::
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit
from PyQt5.QtGui import QKeyEvent
import string
class KeyEventDemo(QWidget):
def __init__(self):
super(KeyEventDemo, self).__init__()
self.resize(500, 500)
self.setMouseTracking(False)
self.te = TextEdit()
self.te.setParent(self)
class TextEdit(QTextEdit):
def __init__(self):
super(TextEdit, self).__init__()
def keyPressEvent(self, e: QKeyEvent) -> None:
QTextEdit.keyPressEvent(self, e)
# 下面写自己需要过滤的代码
if e.text() not in string.hexdigits: # 只有当输入的字符为a时才能显示在QTextEdit中
if e.key() != 16777219:
self.textCursor().deletePreviousChar()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = KeyEventDemo()
window.show()
sys.exit(app.exec_())
还可以通过installEventFilter(filterObj)方法实现,推荐这种,下面的例子是实现只能在QTextEdit中只能输入16进制的数: ?
import sys
import string
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit
from PyQt5.QtCore import QEvent, QObject
# 首先创建一个KeyPressEster类,用于拦截监控对象的按键
class KeyPressEster(QObject):
def eventFilter(self, a0: 'QObject', a1: 'QEvent') -> bool: # a0为当前监控的对象,a1为触发的事件
if a1.type() == QEvent.KeyPress:
print("按键:", a1.text())
if a1.text() in string.hexdigits: # 只能输入16进制的数
a0.textCursor().insertText(a1.text())
if a1.key() == 16777219: # 当按下推个键时,删除字符
a0.textCursor().deletePreviousChar()
return True
else:
return QObject.eventFilter(self, a0, a1)
class FilterDemo(QWidget):
def __init__(self):
super(FilterDemo, self).__init__()
self.resize(500, 500)
self.te = QTextEdit(self)
keyPressEster = KeyPressEster(self) # 实例化按键拦截实例
self.te.installEventFilter(keyPressEster) # 安装过滤器
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FilterDemo()
window.show()
sys.exit(app.exec_())
其他控件也可以设置过滤器,这种方法个人感觉很好用。
|