@eyllanesc's answer is great, but I would like to add that if you have viewport margins set, the position must be adjusted because otherwise it will be offset, and an incorrect cursor position reported.
The doc for cursorForPosition()
states
returns a QTextCursor at position pos (in viewport coordinates). emphasis added
bool PlainTextEdit::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip)
{
QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
QPoint pos = helpEvent->pos();
pos.setX(pos.x() - viewportMargins().left());
pos.setY(pos.y() - viewportMargins().top());
QTextCursor cursor = cursorForPosition(pos);
cursor.select(QTextCursor::WordUnderCursor);
if (!cursor.selectedText().isEmpty())
QToolTip::showText(helpEvent->globalPos(), /*your text*/QString("%1 %2").arg(cursor.selectedText()).arg(cursor.selectedText().length()) );
else
QToolTip::hideText();
return true;
}
return QPlainTextEdit::event(event);
}