简体   繁体   English

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

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

I have a QTextEdit widget which is showing lines of text. 我有一个QTextEdit小部件,它显示文本行。 I want the user to be able to select a block of text to be acted on. 我希望用户能够选择要执行的文本块。 I need to determine the starting and ending line numbers from the complete text that correspond to the selected block. 我需要根据与所选块相对应的全文确定起止行号。

editor.textCursor().blockNumber() gives me the correct starting line number but I haven't been able to find the line number of the ending postion. editor.textCursor().blockNumber()为我提供了正确的起始行号,但我无法找到结束位置的行号。

Finding the length of the selection in lines would be fine. 在行中找到选择的长度会很好。

I'm using PySide and Python 2.7 我正在使用PySide和Python 2.7

Use QTextCursor::selectionStart and QTextCursor::selectionEnd to get block start and end position (as an int ). 使用QTextCursor::selectionStartQTextCursor::selectionEnd获取块的开始和结束位置(作为int )。

Then get copy of the text cursor, use QTextCursor::setPosition to set position to these two, and use QTextCursor::blockNumber to get the line numbers. 然后获取文本光标的副本,使用QTextCursor::setPosition将位置设置为这两个位置,然后使用QTextCursor::blockNumber获取行号。

There may be a shorter way, considering how QTextCursor has quite a lot of methods, but this should work. 考虑到QTextCursor如何使用很多方法,可能会有更短的方法,但这应该可以工作。 You may want to write a helper method, for example one which takes the position and a QTextDocument or QTextCursor , and returns the line number for that position. 您可能需要编写一个辅助方法,例如,一个采用该位置的方法和一个QTextDocumentQTextCursor ,然后返回该位置的行号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM