Thursday, April 6, 2023

Hover over a word to select it then click it to print it

 Another good feature of an integrated development environment (IDE) is its ability to go to the definition of that function/variable/method/class when clicked or double clicked. It saves a lot of time especially when the project involves several thousands of lines of codes spread out over several files. To implement this function, a word must be able to be identified as the mouse hovers it and when selected, it should be clickable, In todays post, I have prepared a simple code snippet to do just that. What the program basically do is in the title itself, select a word by hovering the mouse pointer over it then click it to print it. To take this further, the program must be able to identify the word as a defined variable in the program or a class/method/function. I have already prepared a code snippet to identify if a word is a defined variable as stated on the planner in my chat application project, you may visit the logs here. The portion where I specifically mentioned this can be found at 'Plans for 03/08/2023'

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from PyQt6.QtWidgets import QApplication, QTextEdit
from PyQt6.QtGui import QTextCursor
class HoverTextEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMouseTracking(True)
        self.mousePressEvent = self.onMouseClick
        
        
    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        cursor = self.cursorForPosition(event.pos())
        cursor.select(QTextCursor.SelectionType.WordUnderCursor)
        self.setTextCursor(cursor)
        
    def onMouseClick(self, event):
        super().mousePressEvent(event)
        cursor = self.textCursor()
        if cursor.hasSelection():
            selected_word = cursor.selectedText()
            print(selected_word)
if __name__ == '__main__':
    app = QApplication([])
    widget = HoverTextEdit()
    widget.show()
    app.exec()

No comments:

Post a Comment