开发者社区> 问答> 正文

如何让QPlainTextEdit在键入密钥时自动更正?对于本例,当您键入“<”时,我希望它自动更正

下面是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

展开
收起
kun坤 2019-12-29 21:30:53 343 0
0 条回答
写回答
取消 提交回答
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载