2013-10-07 57 views
4

文字我怎样才能得到光标所在的文本?所以如果我把它放在它上面,那个词是“嗨”,我可以读它吗?我想我需要做QTextCursor.WordUnderCursor的东西,但我真的不知道是什么。任何帮助?PyQt的:获取下光标

这就是我想用现在的工作:

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

我有选择文本,现在只是让我可以看到它。

编辑2:

什么我真的要做的是在显示文本中的某些词提示。

+0

你有一些示例代码,以证明你已经尝试了什么? – 2013-10-07 23:07:31

+0

再次编辑它。 – user2638731

+0

因此,工具提示是否基于下面的单词进行更改?你能提供更多的背景吗? – 2013-10-07 23:16:08

回答

5

不幸的是,我不能在此刻进行测试,所以这是你所需要的最佳猜测。这是基于我编写的一些代码,其中有一个文本框在键入时在工具提示中显示错误,但应该可以工作。

你已经有代码在选择悬停下的话,你只需要在正确的位置的提示。

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()你来填写你没有描述这些,但他们是在什么需要去那里很好地说明了。

关于做好它不选择的话,要做到这一点最简单的方法您的评论是你选择一个新的,然后将其设置回之前缓存光标。您可以拨打,然后像以前那样设置它。

像这样:

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 
+0

非常感谢。我编辑它,它工作得非常好,我只需要找出一种方法来让光标结束而不选择它。如果你有任何想法,你可以给我,这将是伟大的。 – user2638731

+0

@ user2638731我已经包含了文本光标问题的编辑。如果答案有帮助,您可以通过点击回答旁边的勾号来加注或接受它,以向其他用户演示这一点。 – 2013-10-08 01:05:31

+0

Got it!再次感谢您的帮助! :) – user2638731