Tooltip Dissappears when Mouse Cursor Is In Tooltip Content Area

40 Views Asked by At

I am having simple Text Editor. Once I hover on word, the tooltip text which is defined in tooltips dictionary is visible. It works fine. But I have following problem. When tooltip text is too large, it appears at the same position as mouse cursor is located which makes tooltip visible just 1 second.

I have some few tooltips which sometimes cover whole screen. Is it possible to somehow avoid it.

Here is the minimum working code:

Python version: 3.11.0 PyQt5 version: 5.15.7

import sys
from PyQt5.QtWidgets import QTextEdit, QApplication, QMainWindow, QToolTip
from PyQt5.QtGui import QTextCursor


tooltips = {'Hello': ('Tooltip for Hello' * 20 + '\n') * 100 }


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.text_edit = MyTextEdit("Hello")
        self.setCentralWidget(self.text_edit)
        self.resize(800, 600)

class MyTextEdit(QTextEdit):
    def __init__(self, text):
        super().__init__(text)    

    def mouseMoveEvent(self, event):
        tc = self.textCursor()
        
        tc_temp = self.cursorForPosition(event.pos())
        tc_temp.select(QTextCursor.WordUnderCursor)
        word = tc_temp.selectedText()
        
        if word in tooltips:
            self.show_tooltip(tooltips[word])
        else:
            QToolTip.hideText()

        self.setTextCursor(tc)
        
        super().mouseMoveEvent(event)


    def show_tooltip(self, tooltip_text):
        if tooltips:
            pos = self.cursorRect(self.textCursor()).bottomRight()
            pos = self.mapToGlobal(pos)
            QToolTip.showText(pos, tooltip_text)        


app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
0

There are 0 best solutions below