如何获取光标下的文本?因此,如果我将鼠标悬停在它上面并且单词“hi”,我可以阅读它吗?我想我需要用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)
我已经离开了meetCondition()和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,user-interface,qt,pyqt
来源: https://codeday.me/bug/20190529/1176481.html