在QTextEdit中自动添加括号或引号

我需要在QTextEdit中自动添加括号或引号。有没有执行此功能的功能,或者有任何说明此功能的文档?

qqq279985481 回答:在QTextEdit中自动添加括号或引号

您可以覆盖keyPressEvent方法,并在必要时添加相应的文本,同时保持光标位置。

import sys

from PyQt5 import QtCore,QtGui,QtWidgets


class TextEdit(QtWidgets.QTextEdit):
    def keyPressEvent(self,event):
        super().keyPressEvent(event)
        options = {"[": "]","'": "'",'"': '"',"{": "}","(": ")"}
        option = options.get(event.text())
        if option is not None:
            tc = self.textCursor()
            p = tc.position()
            self.insertPlainText(option)
            tc.setPosition(p)
            self.setTextCursor(tc)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = TextEdit()
    w.show()
    sys.exit(app.exec_())
本文链接:https://www.f2er.com/2750854.html

大家都在问