QTextEdit shift-tab错误的行为

时间:2012-11-27 07:11:48

标签: qt qtextedit qplaintextedit

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

看起来是一个没有好解决方案的常见问题。

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

1 个答案:

答案 0 :(得分:2)

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

默认情况下,选项卡会插入一个tabstop,但是下面的代码会捕获一个Qt.Key_Backtab事件,当我按下 Shift + 标签

我尝试了但未能抓住Qt.Key_TabQt.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