[Qt-interest] How can I set to position in QPlainTextEdit?

Daniel Vérité daniel.verite at gmail.com
Tue Dec 30 20:47:43 CET 2008


	 Iurii Gordiienko writes

> Hi In my programm I should find some words and set it's background
> to green color, also I should scroll editor to first word that was
> finds...  I use document()->find and as a result I use
> QPlainTextEditor::setTextCursor(...), but after this sometimes the
> backround of ALL text becomes green... I don't understand
> why... Simple example is attached.  Thanks

Does it happen when the text is changed in the view?
I vaguely recall seeing something like this, when the underlying text 
is changed entirely but the format of the previous text somehow seeems 
to stick.

Anyway, FWIW here is some code that's a bit similar to yours but works 
for me. The main difference is I'm using setExtraSelections().

{
  QList<QTextEdit::ExtraSelection> qlist;
  if (lst.empty()) {
    setExtraSelections(qlist);
    return;
  }
  std::list<searched_text>::const_iterator it = lst.begin();
  QTextEdit::ExtraSelection qsel;
  QTextCharFormat qfmt;
  qfmt.setBackground(QBrush(QColor("yellow")));
  qsel.format = qfmt;
  QTextCursor tcursor;

  QTextDocument::FindFlags flags=0;
  if (it->m_is_cs)
    flags |= QTextDocument::FindCaseSensitively;
  if (it->m_is_word) {
    flags |= QTextDocument::FindWholeWords;
  }

  for ( ; it!=lst.end(); ++it) {
    int index=0;
    do {
      tcursor = document()->find(it->m_text, index, flags);
      if (!tcursor.isNull()) {
	qsel.cursor=tcursor;
	qlist.append(qsel);
	index = tcursor.position()+1;
      }
    } while (!tcursor.isNull());
  }
  setExtraSelections(qlist);	// even if qlist is empty (otherwise we 
get a blank rectangle colored as the selection)
}

Best regards,
-- 
 Daniel
 PostgreSQL-powered mail user agent and storage: 
http://www.manitou-mail.org 



More information about the Qt-interest-old mailing list