qtqtextbrowserqtextcursor

How do I find the position in the document that is visible in a QTextBrowser?


When the user scrolls in a QTextBrowser in my application, I want to retrieve the position in the document that they've scrolled to (offset in the document, not the GUI position.)

If I can make the cursor jump to that location, I can get QTextCursor.position(). But I don't see a way to make the cursor jump to the visible location in the browser. The cursor stays where it is when I scroll.


Solution

  • I do not completely understand the description of your problem, but maybe you can determine the cursor (i.e. the position in text document) of the beginning and the end of the visible area by calling https://doc.qt.io/qt-5/qtextedit.html#cursorForPosition

    QRect rect = textBrowser->rect();
    QTextCursor firstVisible = textBrowser->cursorForPosition(rect.topLeft());
    QTextCursor lastVisible = textBrowser->cursorForPosition(rect.bottomRight());
    

    I have not tested it, but I think you get the idea. Maybe you will need to use the rect of textBrowser->viewport() instead of the rect of textBrowser. You need to experiment a bit with this to find what works for you.