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

问题描述 投票:0回答:1

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

python python-3.x pyqt5 quotes brackets
1个回答
0
投票

您可以覆盖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_())
© www.soinside.com 2019 - 2024. All rights reserved.