如何在 QTextEdit 光标中找到所选内容的开始和结束行号?

How do I find the start and end line number of a selection in QTextEdit cursor?

我有一个显示文本行的 QTextEdit 小部件。我希望用户能够对 select 一段文本进行操作。我需要从与 selected 块相对应的完整文本中确定开始和结束行号。

editor.textCursor().blockNumber() 给了我正确的起始行号,但我找不到结束位置的行号。

找到 selection 的长度就可以了。

我正在使用 PySide 和 Python 2.7

使用 QTextCursor::selectionStart and QTextCursor::selectionEnd 获取块的开始和结束位置(作为 int)。

然后获取文本光标的副本,使用QTextCursor::setPosition to set position to these two, and use QTextCursor::blockNumber获取行号。

考虑到 QTextCursor 有很多方法,可能有更短的方法,但这应该可行。您可能想要编写一个辅助方法,例如一个获取位置和 QTextDocumentQTextCursor 以及 returns 该位置的行号的方法。