gpt4 book ai didi

QTextEdit shift-tab 错误行为

转载 作者:行者123 更新时间:2023-12-04 05:22:14 25 4
gpt4 key购买 nike

shift+tab 在 QTextEdit/QPlainTextEdit 中表现为 tab。

看起来像一个普遍的问题,没有好的解决方案。

当 tab 增加缩进级别而 shift-tab 减少它时,是否有任何“经典”的方法来启用此功能?

最佳答案

这是一个老问题,但我想通了。
您只需要使用继承自它的自己的类重新实现 QPlainTextEdit(或 QTextEdit),并覆盖 keyPressEvent。

默认情况下,制表符会插入制表位,但下面的代码会捕获 Qt.Key_Backtab事件,据我所知,这是按 Shift+Tab 时发生的事件。

我试过但没能 catch Qt.Key_Tab和一个 Qt.Key_ShiftQt.Key_Tab和一个 Shift 修饰符,所以这必须是这样做的方法。

import sys
from PyQt4 import QtCore, QtGui

class TabPlainTextEdit(QtGui.QTextEdit):
def __init__(self,parent):
QtGui.QTextEdit.__init__(self, parent)

def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Backtab:
cur = self.textCursor()
# Copy the current selection
pos = cur.position() # Where a selection ends
anchor = cur.anchor() # Where a selection starts (can be the same as above)

# Can put QtGui.QTextCursor.MoveAnchor as the 2nd arg, but this is the default
cur.setPosition(pos)

# Move the position back one, selection the character prior to the original position
cur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)

if str(cur.selectedText()) == "\t":
# The prior character is a tab, so delete the selection
cur.removeSelectedText()
# Reposition the cursor with the one character offset
cur.setPosition(anchor-1)
cur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)
else:
# Try all of the above, looking before the anchor (This helps if the achor is before a tab)
cur.setPosition(anchor)
cur.setPosition(anchor-1,QtGui.QTextCursor.KeepAnchor)
if str(cur.selectedText()) == "\t":
cur.removeSelectedText()
cur.setPosition(anchor-1)
cur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)
else:

# Its not a tab, so reset the selection to what it was
cur.setPosition(anchor)
cur.setPosition(pos,QtGui.QTextCursor.KeepAnchor)
else:
return QtGui.QTextEdit.keyPressEvent(self, event)

def main():
app = QtGui.QApplication(sys.argv)
w = TabPlainTextEdit(None)
w.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()

我仍在完善这个,但 rest of the code is on GitHub .

关于QTextEdit shift-tab 错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13579116/

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