Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to navigate QPlainTextEdit / QTextBrowser



  • I have a long QString (plain text) and an index for it. Say, the string is a book and I know where each chapter starts in it. The string is displayed using QPlainTextEdit (or maybe QTextBrowser - doesn't matter much, it's just that scrolling huge text is smoother in the former).

    How can I navigate between chapters in the text viewer? I know I can use QTextCursor to go to a specific line in the widget, but knowing line numbers for the source string will do me no good since there are huge paragraphs and line wrapping will engage, so I have no way of knowing how the source string's lines will correspond to the view's lines.

    Ideas?

    Can I use hypertext (which was more or less designed just for this)? Rich text and anchors?



  • You can indeed use QTextCursor.
    assume QPlainTextEdit * plainTextEdit and you want to reach the character at position int charIndex

    plainTextEdit->moveCursor(QTextCursor::Start);
    for(int i=0;i<charIndex;++i)
    plainTextEdit->moveCursor(QTextCursor::NextCharacter);
    


  • @VRonin
    That's easy enough! Won't it be slow when I have to move to the character number 1 million?



  • If it is you can try:

    plainTextEdit->moveCursor(QTextCursor::Start);
    QTextCursor txtCur=plainTextEdit->textCursor();
    txtCur.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,charIndex);
    plainTextEdit->setTextCursor(txtCur);
    

    but I suspect that internally the same thing happens to the cursor as the for loop case



  • @VRonin
    I suspect the widget updated is queued every time, and the question is whether or not 1 million updates will collapse into one. I'll know soon enough. Regardless, the second version looks cleaner to me, even though it's more verbose.



  • @VRonin
    It works! Except with a 1.58 million characters Unicode text executing movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,charIndex) takes the longer the larger charIndex gets. In the end it reaches 4.0 seconds on my core i5-2500 CPU @ 3.8 GHz.
    But I don't suppose something can be done about that?..



  • Fixed the problem. QTextCursor has a method setPosition that works instantly. So instead of

    txtCur.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,charIndex);

    I simply did

    txtCur.setPosition(charIndex);

    And now there's no performance issues.


Log in to reply