Search code examples
qttooltip

Qt: measure tooltip height, or anchor tooltip from bottom


I have the following code to place a tooltip at text-cursor position in a QLineEdit (i.e. the bottom left corner of the tooltip stays just above the text cursor):

    setToolTip(tip);

    QPoint cur = mapToGlobal(cursorRect().topLeft());
    QHelpEvent *event = new QHelpEvent(QEvent::ToolTip,
            QPoint(pos().x(), pos().y()),
            QPoint(cur.x(), cur.y() - 2 * height() - 2));
    QApplication::postEvent(this, event);

I roughly estimated tooltip height as QLineEdit::height(), but that's wrong, and becomes terribly wrong when the tooltip wraps on multiple lines, because it would cover the line edit.

Is there a way to measure a tooltip text height? Or a way to place a tooltip by specifying the bottom-left or bottom-center as anchor point?


Solution

  • It seems using QFontMetrics with QToolTip::font() works fine.

    Here's my solution:

        setToolTip(tip);
    
        QFontMetrics fm(QToolTip::font());
        QRect r = fm.boundingRect(QRect(0, 0, 500, 50), 0, tip);
    
        QPoint cur = mapToGlobal(cursorRect().topLeft());
        QHelpEvent *event = new QHelpEvent(QEvent::ToolTip,
                QPoint(pos().x(), pos().y()),
                QPoint(cur.x(), cur.y() - height() - r.height() - 4));
        QApplication::postEvent(this, event);