2

shift + tabは、QTextEdit/QPlainTextEditのタブとして動作します。

良い解決策がない一般的な問題のように見えます。

タブがインデントレベルを上げ、Shift-Tabがインデントレベルを下げるときに、この機能を有効にする「古典的な」方法はありますか?

4

1 に答える 1

3

これは少し古い質問ですが、私はこれを理解しました。QPlainTextEdit (または QTextEdit) を継承する独自のクラスで再実装し、keyPressEvent をオーバーライドするだけです。

デフォルトでは、タブはタブストップを挿入しますが、以下のコードはQt.Key_Backtabイベントをキャッチします。これは、 Shift+を押したときに発生するイベントですTab

Qt.Key_TabQt.Key_Shiftorと Shift 修飾子をキャッチしようとして失敗したQt.Key_Tabので、これがその方法であるに違いありません。

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 にあります

于 2013-08-03T11:21:58.223 に答える