【问题标题】:Pyqt: Get text under cursorPyqt:获取光标下的文本
【发布时间】:2013-10-14 16:40:49
【问题描述】:

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

这就是我现在正在尝试使用的:

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

我现在让它选择文本,以便我可以看到它。

编辑 2:

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

【问题讨论】:

  • 您有一些示例代码来演示您尝试过的内容吗?
  • 那么工具提示会根据下面的单词而改变吗?你能提供更多的背景信息吗?
  • 是的,如果它匹配一个单词,在单词列表中,我需要它为每个单词显示一个特定的工具提示。我只是在工具提示部分遇到问题。谢谢。

标签: python qt user-interface pyqt


【解决方案1】:

很遗憾,我目前无法对此进行测试,因此这是对您需要的最佳猜测。这是基于我编写的一些代码,该代码有一个文本字段,在您键入时会在工具提示中显示错误,但应该可以工作。

您已经有了代码来选择悬停下的单词,您只需要在正确的位置显示工具提示。

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)

我已将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

【讨论】:

  • 非常感谢。我编辑了它,它工作得很好;我只需要想出一种方法来获取光标所在的单词而不选择它。如果你有什么想法可以给我,那就太好了。
  • @user2638731 我已经对文本光标问题进行了编辑。如果某个答案有帮助,您可以通过点击答案旁边的勾号来支持或接受它,从而向其他用户展示这一点。
  • 知道了!再次感谢您的帮助! :)
猜你喜欢
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多