Sivo 悉见

PyQt5的QTextCursor 如何使用

匿名 · 更新于 2018/4/16

Q: QTextCursor 如何使用?

API参考

前提条件:获得指针对象

textCursor = self.textEdit.textCursor()
  • 获取指定区间的文本(相对于整篇文档)

    <pre class="hljs lsl" style="box-sizing: border-box; overflow: auto; font-family: &quot;Source Code Pro&quot;, Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 0.93em; padding: 1em; margin-bottom: 1.5em; line-height: 1.45; word-break: break-all; background: url(&quot;../img/blueprint.png&quot;) 0% 0% / 30px, 0% 0% / 30px rgb(246, 246, 246); border: none; border-radius: 4px; max-height: 35em; position: relative; margin-top: 0px !important;">
    

    textCursor.setPosition(3, QTextCursor.MoveAnchor) textCursor.setPosition(9, QTextCursor.KeepAnchor) lineContent = textCursor.selectedText()

str = '0123456789'
3-9之间的字符为 345678

  • 获取光标所在行的文本

    <pre class="hljs abnf" style="box-sizing: border-box; overflow: auto; font-family: &quot;Source Code Pro&quot;, Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 0.93em; padding: 1em; margin-bottom: 1.5em; line-height: 1.45; word-break: break-all; background: url(&quot;../img/blueprint.png&quot;) 0% 0% / 30px, 0% 0% / 30px rgb(246, 246, 246); border: none; border-radius: 4px; max-height: 35em; position: relative; margin-top: 0px !important;">
    

    textCursor.select(QTextCursor.LineUnderCursor) lineContent = textCursor.selectedText()

  • 获取光标所在行的文本的前5个字符

    <pre class="hljs arduino" style="box-sizing: border-box; overflow: auto; font-family: &quot;Source Code Pro&quot;, Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 0.93em; padding: 1em; margin-bottom: 1.5em; line-height: 1.45; word-break: break-all; background: url(&quot;../img/blueprint.png&quot;) 0% 0% / 30px, 0% 0% / 30px rgb(246, 246, 246); border: none; border-radius: 4px; max-height: 35em; position: relative; margin-top: 0px !important;">
    

    textCursor.movePosition(QTextCursor.StartOfLine) end = textCursor.position() + 5 textCursor.setPosition(end, QTextCursor.KeepAnchor)