1

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

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);

然而,结果很奇怪。当我第一次单击文本时,什么也没发生,有时可能选择了一个词。然后我再次单击,前一行和上一行将突出显示。我不明白为什么会这样。谁能给我一些解决方案?谢谢。

4

2 回答 2

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);
}
于 2014-03-28T09:48:06.677 回答
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);
        }
于 2018-01-11T10:40:01.087 回答