Documentation on QTextEdit::cursorForPosition says it accepts coordinates relative to viewport.
Do you pass mouse position in viewport coordinates?
Documentation on QTextEdit::cursorForPosition says it accepts coordinates relative to viewport.
Do you pass mouse position in viewport coordinates?
Thank you for your reply. Initially I didn't pass position in viewport coordinates, but directly the event->pos(). However, converting to viewport coordinates (by re-implementing viewportEvent() rather than event()) hardly made any difference (1 pixel at most: there is no scrolling).
Actually, this shifting between the character(s) and the cursor position is consistent with what the documentation says about QTextCursor: "The cursor's current position() then is always either between two consecutive characters...".
QTextEdit::cursorForPosition() returns a cursor (rather obviously), the cursor is between two characters (plus special cases at text ends) and the position returned is the cursor position nearest to the mouse cursor. For far so good: everything is consistent ans reasonable.
The problem however remains: how to retrieve the character physically underneath the mouse pointer, regardless of where a text cursor would be placed by clicking 'there'?
Any hint about where to look for other API's more convenient for this task would be welcome (perhaps not passing via cursors at all): I could not find any.
Thanks,
M.
Try the following:
Qt Code:
// m_Edit - QTextEdit object // ptViewport - mouse position in viewport coordinates // docLPos - position of character under mouse int docLPos = m_Edit->document()->documentLayout()->hitTest( QPointF( ptViewport.x(), ptViewport.y() ), Qt::ExactHit );To copy to clipboard, switch view to plain text mode
Thanks for the reply and my apologies for the delay in acknowledging it: the project has been suspended and I completely forgot about this pending issue.
I was aware of the hitTest() function, but I assumed it was working the same as cursorForPosition() (oh, never, never assume anything!), so I did not even tried it.
When finally answering your post, in order to give a complete reply as possible, I tried it and, lo!, it works indeed!.
So, thanks for overriding my stubborness!
M.
Bookmarks