gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:08:34 25 4
gpt4 key购买 nike

我需要在 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_())

关于python - 在 QTextEdit 中自动添加括号或引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59792382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com