利用QTextCursor取得指針位置,修改選取參數查看顯示效果
QTextCursor選取參數:
- Document 3 Selects the entire document. 選取全部
- BlockUnderCursor 2 Selects the block of text under the cursor. 選取到cursor位置的block
- LineUnderCursor 1 Selects the line of text under the cursor. 選取與cursor位置同一行
- WordUnderCursor 0 Selects the word under the cursor. 選取cursor位置的單字
EX: Document
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout import sys class TextEditDemo(QWidget): def __init__(self, parent=None): super(TextEditDemo, self).__init__(parent) self.setWindowTitle("QTextEdit") self.resize(300, 150) self.textEdit = QTextEdit() layout = QVBoxLayout() layout.addWidget(self.textEdit) self.setLayout(layout) s = "12345 6789\n12345 6789\n12345 6789""" self.textEdit.setText(s) cursor = self.textEdit.textCursor() # 將指針移動到第二行位置 cursor.setPosition(11) # 選取全部 cursor.select(QTextCursor.Document) self.textEdit.setTextCursor(cursor) if __name__ == "__main__": app = QApplication(sys.argv) win = TextEditDemo() win.show() sys.exit(app.exec_()) |
全部選取效果(Document)
依序測試其他效果
BlockUnderCursor
LineUnderCurosr
WordUnderCursor