Home > front end >  How do I find the position in the document that is visible in a QTextBrowser?
How do I find the position in the document that is visible in a QTextBrowser?

Time:10-30

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.

CodePudding user response:

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.

CodePudding user response:

Based on V.K.'s answer, here is my solution in Python:

browserRect = self.mainText.rect()
newCursor = self.mainText.cursorForPosition(browserRect.topLeft())
self.mainText.setTextCursor(newCursor)
textPos = mainText.textCursor().position()

Actually, just using QPoint(0,0) probably would work just as well, since the upper left of the browser's rectangle is pretty close to (0,0).

  • Related