下面是QLineEdit的解决方案。这个可以为QPlainTextEdit修复吗?如何让QPlainTextEdit在键入密钥时自动更正?对于本例,当您键入“<”时,我希望它自动更正为“小于”。
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QCompleter, QGridLayout, QLineEdit, QWidget
class LineEdit(QLineEdit):
def __init__(self, mapping, parent=None):
super(LineEdit, self).__init__(parent)
self.mapping = mapping
def keyPressEvent(self, event):
last_text = self.text()
super(LineEdit, self).keyPressEvent(event)
new_text = self.text()
if last_text + event.text() == new_text:
new_text = self.mapping.get(event.text())
if new_text is not None:
self.setText(last_text + new_text)
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
layout = QGridLayout(self)
#names = ["Apple", "Alps", "Berry", "Cherry"]
#completer = QCompleter(names)
mapping = {"<": "less than", ">": "greater than", "'": "`"}
self.lineedit = LineEdit(mapping)
#self.lineedit.setCompleter(completer)
layout.addWidget(self.lineedit, 0, 0)
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())
我尝试以下并收到:QKeyEvent对象没有属性' to明文' 返回到行的引用:new_text = self.mapping.get(event. to明文())
class LineEdit(QPlainTextEdit):
def __init__(self, mapping, parent=None):
super(LineEdit, self).__init__(parent)
self.mapping = mapping
def keyPressEvent(self, event):
last_text = self.toPlainText()
super(LineEdit, self).keyPressEvent(event)
new_text = self.toPlainText()
if last_text + event.text() == new_text:
new_text = self.mapping.get(event.toPlainText())
if new_text is not None:
self.setPlainText(last_text + new_text)
问题来源StackOverflow 地址:/questions/59380082/how-do-i-have-a-qplaintextedit-auto-correct-when-a-key-is-typed-for-this-exampl
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。