在Qt中选择鼠标指针下的单词
当我在QTextBrowser中单击鼠标右键时,我需要高亮显示并在鼠标指针下获取单词。我已经为鼠标右键单击的QTextBrowser实现了showContextMenu功能。但是,我不能突出显示鼠标指针下的单词并提取它。我在网上找到了以下解决方案:在Qt中选择鼠标指针下的单词,qt,Qt,当我在QTextBrowser中单击鼠标右键时,我需要高亮显示并在鼠标指针下获取单词。我已经为鼠标右键单击的QTextBrowser实现了showContextMenu功能。但是,我不能突出显示鼠标指针下的单词并提取它。我在网上找到了以下解决方案: QTextCursor tc = txtBrwsr->textCursor(); tc.select(QTextCursor::WordUnderCursor); QString word = tc.selectedText(); 但是,它不
QTextCursor tc = txtBrwsr->textCursor();
tc.select(QTextCursor::WordUnderCursor);
QString word = tc.selectedText();
但是,它不起作用,单词是空的,我的目标是获取该单词并高亮显示它,即使用户在按下鼠标右键之前没有高亮显示该单词
非常感谢您的帮助。textCursor()
函数返回QTextCursor的副本。
您需要在所有更改之后调用setTextCursor()
这是一个在鼠标右键单击后如何突出显示鼠标光标下的单词的示例
MyTextBrowser.h
MyTextBrowser.cpp
void MyTextBrowser::MousePresseEvent(QMouseEvent*mouseEvent){
如果(Qt::RightButton==mouseEvent->button()){
qtextcursortextcursor=cursorForPosition(mouseEvent->pos());
textCursor.select(QTextCursor::wordundersor);
setTextCursor(textCursor);
QString word=textCursor.selectedText();
qDebug()使用txtBrwsr->setTextCursor(tc);
在tc之后选择(…)
。我试过你的例子,它对我有用(qt4.8.1,Mac)。
class MyTextBrowser : public QTextBrowser {
// ...
protected:
void mousePressEvent(QMouseEvent *mouseEvent);
// ...
};
void MyTextBrowser::mousePressEvent(QMouseEvent *mouseEvent) {
if (Qt::RightButton == mouseEvent->button()) {
QTextCursor textCursor = cursorForPosition(mouseEvent->pos());
textCursor.select(QTextCursor::WordUnderCursor);
setTextCursor(textCursor);
QString word = textCursor.selectedText();
qDebug() << word;
}
QTextBrowser::mousePressEvent(mouseEvent);
}