Question

In my textbrowser, I've already implemented the mousePress and found the line number when clicked. Now I want to highlight where I clicked i.e., change its background color. I knew line is different with block. Luckily in my text one line is one block. So What I did is to manipulate the block format by cursor, listed as follows:

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

However, the result is odd. When I first click the text, nothing happened, sometimes maybe selected a word. Then I click again, that previous line and the above line would be highlighted. I don't understand why this happened. Could anyone give me some solutions? Thanks.

Was it helpful?

Solution

Your code doesn't even compile. It uses QBlockFormat class that doesn't exist and cur.selection with invalid argument. Did you just type it out of your head? Anyway, why don't you use LineUnderCursor instead? The following code works fine for me:

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

OTHER TIPS

This is what i use it works for both QTextEdit and QTextBrowser:

textBrowser is QTextBrowser in example below.

        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);
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top