Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create tooltip for highlighted strings in QPlainTextEdit

I have a QPlainTextEdit and have some words highlighted in it now I want when I hover over it with the mouse it show me a tooltip that has description or something like that about this highlighted word something like this in QT IDE

enter image description here

but I don't know how to start this so any idea, code or similar project to check this.

like image 245
user7179690 Avatar asked Mar 08 '17 17:03

user7179690


2 Answers

For this case I will create a class that inherits from QPlainTextEdit, reimplement the event() method and enable mouse tracking with setMouseTracking()

plaintextedit.h

#ifndef PLAINTEXTEDIT_H
#define PLAINTEXTEDIT_H

#include <QPlainTextEdit>

class PlainTextEdit : public QPlainTextEdit
{
public:
    PlainTextEdit(QWidget *parent=0);

    bool event(QEvent *event);
};

#endif // PLAINTEXTEDIT_H

plaintextedit.cpp

#include "plaintextedit.h"
#include <QToolTip>


PlainTextEdit::PlainTextEdit(QWidget *parent):QPlainTextEdit(parent)
{
    setMouseTracking(true);
}

bool PlainTextEdit::event(QEvent *event)
{
    if (event->type() == QEvent::ToolTip)
    {
        QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
        QTextCursor cursor = cursorForPosition(helpEvent->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);
}

Complete Code: Here

like image 115
eyllanesc Avatar answered Nov 19 '22 10:11

eyllanesc


@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);
}
like image 3
namezero Avatar answered Nov 19 '22 12:11

namezero