Pyqt:在光标下获取文本

use*_*731 4 python user-interface qt pyqt

如何获取光标下的文本?因此,如果我将鼠标悬停在它上面并且单词"hi",我可以阅读它吗?我想我需要用QTextCursor.WordUnderCursor做一些事情,但我不确定是什么.有帮助吗?

这就是我现在正在努力解决的问题:

    textCursor = text.cursorForPosition(event.pos());
    textCursor.select(QTextCursor.WordUnderCursor);
    text.setTextCursor(textCursor);
    word = textCursor.selectedText();
Run Code Online (Sandbox Code Playgroud)

我现在正在选择文本,所以我可以看到它.

编辑2:

我真正想要做的是在文本中的某些单词上显示工具提示.

小智 6

不幸的是,我现在无法测试这一点,所以这是对你需要的最佳猜测.这是基于我编写的一些代码,它有一个文本字段,在您输入的工具提示中显示错误,但应该有效.

你已经有了代码来选择悬停的单词,你只需要在正确的位置输入工具提示.

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)
Run Code Online (Sandbox Code Playgroud)

我已经离开了meetsSomeCondition(),并toolTipFromWord()给你填写你没有描述这些,但他们是在什么需要去那里很好地说明了.

至于做它没有选择的话你的评论,要做到这一点最简单的方法是选择一个新的,然后将其设置回之前缓存光标.您可以通过调用QTextEdit.textCursor()然后像以前一样设置它来完成此操作.

像这样:

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
Run Code Online (Sandbox Code Playgroud)