1

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.

TonyLic
  • 647
  • 1
  • 13
  • 26

2 Answers2

1

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);
}
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Thanks. Actually I used the same way as you gave. Those are typos because the real code is in a computer without internet so I have to type them manually. Anyway, in this method, the problem is that when I click a line, say 5, it has no respond. However, next time I click another line, the line 5 would be highlighted. Would you please tell me why?? – TonyLic Apr 04 '14 at 19:46
  • Basically, this is the right answer. But I think "ui->textBrowser->setTextCursor(cur)" is not needed because it may causes additional highlight. Also, in my program, I calculate the cursor position where clicked and use the setCursorPosition. Anyway, thanks a lot! – TonyLic Apr 08 '14 at 20:04
0

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);
        }
Keshav Bhatt
  • 171
  • 1
  • 5