shift+tab 表现为 QTextEdit/QPlainTextEdit 中的选项卡。
看起来像一个没有好的解决方案的常见问题。
当 tab 增加缩进级别而 shift-tab 降低缩进级别时,是否有任何“经典”方式来启用此功能?
shift+tab 表现为 QTextEdit/QPlainTextEdit 中的选项卡。
看起来像一个没有好的解决方案的常见问题。
当 tab 增加缩进级别而 shift-tab 降低缩进级别时,是否有任何“经典”方式来启用此功能?
这是一个老问题,但我明白了。您只需要使用您自己的继承自它的类重新实现 QPlainTextEdit(或 QTextEdit),并覆盖 keyPressEvent。
默认情况下,选项卡会插入一个制表位,但下面的代码会捕获一个Qt.Key_Backtab
事件,据我所知,这是您按下Shift+时发生的事件Tab。
我尝试并未能捕捉Qt.Key_Tab
到一个Qt.Key_Shift
orQt.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()
我仍在完善它,但其余代码在 GitHub 上。