簡體   English   中英

Python PyQt5 - 選擇插入的 cursor 文本?

[英]Python PyQt5 - Selecting inserted cursor text?

我有一個 QPlainTextEdit 小部件,並且正在嘗試讓 cursor 自動 select 插入的文本。 我目前的方法是使用 QTextCursor.WordLeft 向后 select 因為 using.insertText() 將 cursor 移動到該單詞的末尾。 謝謝!

編輯:進一步澄清:理想情況下,我希望插入的文本突出顯示,cursor 放置在插入的單詞的開頭。 例如: State 1 -> State 2

State 1 顯示一個輸入字。 然后,一旦用戶點擊空格鍵,程序就會插入一個單詞,突出顯示它,並將 cursor 放在該插入單詞的開頭,如 State 2 所示。

class TextBox(QPlainTextEdit):
    def __init__(self):
        QPlainTextEdit.__init__(self)

        font = QtGui.QFont()
        font.setPointSize(12)
        self.setFont(font)

    def keyPressEvent(self, keyEvent):
        super(TextBox, self).keyPressEvent(keyEvent)

        if keyEvent.key()  == Qt.Key_Return :
            self.clear()

        elif keyEvent.key() == Qt.Key_Space:
            cursor = self.get_cursor()
            cursor.insertText("test")    # The area of concern
            cursor.selectionStart()
            cursor.movePosition(QtGui.QTextCursor.WordLeft, QtGui.QTextCursor.KeepAnchor, 1)
            cursor.selectionEnd()
            # Moving the cursor position doesn't seem to do anything


    def get_cursor(self):
        return self.textCursor()

    def get_cursor_pos(self):
        return self.get_cursor().position()

您缺少的是,要應用 cursor position 和選擇,必須將 cursor 設置回文本編輯。

class TextBox(QPlainTextEdit):
    # ...

    def keyPressEvent(self, keyEvent):
        super(TextBox, self).keyPressEvent(keyEvent)

        if keyEvent.key()  == Qt.Key_Return :
            self.clear()

        elif keyEvent.key() == Qt.Key_Space:
            cursor = self.textCursor()
            cursor.insertText("test")
            cursor.movePosition(QtGui.QTextCursor.WordLeft, QtGui.QTextCursor.KeepAnchor, 1)
            self.setTextCursor(cursor)

請記住,由於您調用的是 keyPressEvent 的基本 class 實現,因此您總是會在“新”文本之前有一個空格。 如果出於某種原因您想避免這種情況,那么每當您獲得空格鍵時都必須忽略它。

    def keyPressEvent(self, keyEvent):
        if keyEvent.key()  == Qt.Key_Return :
            self.clear()

        elif keyEvent.key() == Qt.Key_Space:
            cursor = self.textCursor()
            pos = cursor.position()
            cursor.insertText("test")
            cursor.setPosition(pos, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
            # by returning, the event won't be sent to the default implementation
            return

        super(TextBox, self).keyPressEvent(keyEvent)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM