QTextEdit select a line of text

QTextEdit select a line of text

Because to do an RPG game in the kind of dialogue display module, each page can be displayed due to space is limited, so it is necessary to know which page to display text. And this needs to know which line of text can be displayed.

Internet search of the investigation related to the solution, but found not practice a bit, so their own research a bit to find a solution.

Let me talk about ideas: use QTextCursor members of QTextEdit. QTextCursor members have some methods can be easily manipulated text, such as a row select cursor, moves the cursor or the like.

    QTextCursor textCursor = ui->textWidget->textCursor();
    textCursor.movePosition(QTextCursor::Start);   //将光标移动到起始位置
    textCursor.select(QTextCursor::LineUnderCursor);
    QString curText = textCursor.selectedText();

But when this text is selected, qt will automatically remove trailing spaces or line, if one end of the line just a space, in this way you will find that space gone, if you need the space at the end of lines or change, this time you need to do deal with.

    //刚刚行全选完的行尾作为起始位置   
    textCursor.setPosition(textCursor.position(),QTextCursor::MoveAnchor);  
    //向后移动光标,选中一个字符
    textCursor.setPosition(textCursor.position()+1,QTextCursor::KeepAnchor); 
    QString endCharactor = textCursor.selectedText();
    if(endCharactor == " "||endCharactor=="\n")
    //Do Something

In this way, we can achieve the desired effect of perfect.

Guess you like

Origin www.cnblogs.com/AlainGao/p/12400605.html