user2638731
user2638731

Reputation: 605

Pyqt: Get text under cursor

How can I get the text under the cursor? So if I hover over it and the word was "hi" I could read it? I think I need to do something with QTextCursor.WordUnderCursor but I am not really sure what. Any help?

This is what I am trying to work with right now:

    textCursor = text.cursorForPosition(event.pos());
    textCursor.select(QTextCursor.WordUnderCursor);
    text.setTextCursor(textCursor);
    word = textCursor.selectedText();

I have it selecting the text right now just so I can see it.

Edit 2:

What I am really trying to do is display a tooltip over certain words in the text.

Upvotes: 7

Views: 4575

Answers (1)

user764357
user764357

Reputation:

Unfortunately, I can't test this at the moment, so this is a best guess at what you need. This is based on some code I wrote that had a textfield that showed errors in a tooltip as you typed, but should work.

You've already got code to select the word under the hover over, you just need the tooltip in the right spot.

textCursor = text.cursorForPosition(event.pos())
textCursor.select(QTextCursor.WordUnderCursor)
text.setTextCursor(textCursor)
word = textCursor.selectedText()

if meetsSomeCondition(word):
    toolTipText = toolTipFromWord(word)
    # Put the hover over in an easy to read spot
    pos = text.cursorRect(text.textCursor()).bottomRight()
    # The pos could also be set to event.pos() if you want it directly under the mouse
    pos = text.mapToGlobal(pos)
    QtGui.QToolTip.showText(pos,toolTipText)

I've left meetsSomeCondition() and toolTipFromWord() up to you to fill in as you don't describe those, but they are pretty descriptive in what needs to go there.

Regarding your comment on doing it without selecting the word, the easiest way to do this is to cache the cursor before you select a new one and then set it back. You can do this by calling QTextEdit.textCursor() and then setting it like you did previously.

Like so:

oldCur = text.textCursor()
textCursor.select(QTextCursor.WordUnderCursor) # line from above
text.setTextCursor(textCursor)                 # line from above
word = textCursor.selectedText()               # line from above
text.setTextCursor(oldCur)

# if condition as above

Upvotes: 8

Related Questions