gpt4 book ai didi

python - Pyqt:获取光标下的文本

转载 作者:太空狗 更新时间:2023-10-30 02:32:17 24 4
gpt4 key购买 nike

如何获取光标下的文字?所以,如果我将鼠标悬停在它上面并且这个词是“嗨”,我能读懂它吗?我想我需要用 QTextCursor.WordUnderCursor 做点什么,但我不太确定是什么。有帮助吗?

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

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

我现在让它选择文本,这样我就可以看到它。

编辑 2:

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

最佳答案

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

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

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

关于python - Pyqt:获取光标下的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19236165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com