键入时如何自动更正QLineEdit?

时间:2019-12-13 23:11:21

标签: python pyqt pyqt5 qlineedit

键入键后,如何自动校正QLineEdit? 对于此示例,当您键入“ <”时,我希望它自动更正为“小于”。

from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QGridLayout()
        self.setLayout(layout)

        # auto complete options                                                 
        names = ["Apple", "Alps", "Berry", "Cherry" ]
        completer = QCompleter(names)

        # create line edit and add auto complete                                
        self.lineedit = QLineEdit()
        self.lineedit.setCompleter(completer)
        layout.addWidget(self.lineedit, 0, 0)


app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

您可以检查是否添加了字符,如果已添加,请替换QLineEdit文本。可以覆盖keyPressEvent方法的可能实现:

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_())