2014-03-27 69 views
1

在我的文本浏览器中,我已经实现了mousePress并在点击时找到了行号。现在我想突出显示我点击的位置,即更改其背景颜色。我知道线与块不同。幸运的是,在我的文本中,一行是一个块。所以,我没有什么是通过操纵光标块格式如下:QTextBrowser:如何突出点击线

QTextCursor cur = mytextBrowser->textCursor(); 
QBlockFormat f; 
f.setBackground(Qt::red); 
cur.selection(QTextCursor::BlockUnderCursor); 
cur.setBlockFormat(f); 
cur.setPosition(startPos);//I calculate this startPos before. It's where the cursor should be 
mytextBrowser->setTextCursor(cur); 

但是,结果是奇数。当我第一次点击文本时,什么也没有发生,有时候可能会选择一个词。然后我再次点击,上一行和上面的行会突出显示。我不明白为什么会发生这种情况。谁能给我一些解决方案?谢谢。

回答

1

你的代码甚至没有编译。它使用不存在的QBlockFormat类和具有无效参数的cur.selection。你只是把它从头脑中打出来了吗?无论如何,你为什么不用LineUnderCursor呢?下面的代码工作正常,我:

void MainWindow::on_textBrowser_cursorPositionChanged() { 
    QTextCursor cur = ui->textBrowser->textCursor(); 
    QTextBlockFormat f; 
    f.setBackground(Qt::red); 
    cur.select(QTextCursor::LineUnderCursor); 
    cur.setBlockFormat(f); 
    ui->textBrowser->setTextCursor(cur); 
} 
+0

谢谢。其实我用的是和你一样的方式。这些都是拼写错误,因为真正的代码是在没有互联网的计算机上,所以我必须手动键入它们。无论如何,在这种方法中,问题是当我点击一行时,说5,它没有回应。但是,下次单击另一行时,第5行将突出显示。你能告诉我为什么? – TonyLic

+0

基本上,这是正确的答案。但我认为“ui-> textBrowser-> setTextCursor(cur)”是不需要的,因为它可能会导致额外的高亮。另外,在我的程序中,我计算光标位置点击并使用setCursorPosition。无论如何,非常感谢! – TonyLic

0

这是我使用它同时适用于的QTextEdit和QTextBrowser:

textBrowser是QTextBrowser下面的例子英寸

 void MainWindow::on_textBrowser_cursorPositionChanged(){ 
      QTextBrowser::ExtraSelection selection ; 
      QColor lineColor = QColor(201, 191, 253, 15); 
      selection.format.setBackground(lineColor); 
      selection.format.setProperty(QTextFormat::FullWidthSelection, true); 
      selection.cursor = ui->textBrowser->textCursor(); 
      selection.cursor.clearSelection(); 
      extraSelections.append(selection); 
      ui->textBrowser->setExtraSelections(extraSelections); 
     }