Do you want to have like following in text ?

4 + <Time> + 5

We can do it either by highlighting the ‘<Time>’ or by setting the format.

First of all, create a class inherits QTextEdit, say MyTextEdit.


By Highlighting

In this method, it needs to create one more class which now inherits QSyntaxHighlighter, say MyHighlighter.

The implementation of class MyHighlighter could look like the following.

MyHighlighter::MyHighlighter(MyTextEdit *mte) : QSyntaxHighlighter(mte)
{
  objectFormat.setForeground(Qt::red);
  objectPattern = QRegExp("<[^<]*>");
}

MyHighlighter::~MyHighlighter()
{}

void MyHighlighter::highlightBlock(const QString &text)
{
  int index = objectPattern.indexIn(text);

  while (index >= 0)
    {
      int length = objectPattern.matchedLength();
      setFormat(index, length, objectFormat);
      index = objectPattern.indexIn(text, index + length);
    }
}

whereas in the header:

class MyHighlighter: public QSyntaxHighlighter
{
public:
  MyHighlighter(MyTextEdit* mte);
  ~MyHighlighter();

protected:
  void highlightBlock(const QString &text);

public:
  QTextCharFormat objectFormat;
  QRegExp objectPattern;
};

Look at implementation codes line 4. We applies QRegExp to identify the format ‘<xxx>’ in whole text and color it by red at line 3. All these tasks is defined in function highlightBlock. This function is called when necessary by the rich text engine, i.e. on text blocks which have changed.

All we need is just to create an object in constructor of class MyTextEdit.

MyTextEdit:: MyTextEdit(QWidget * parent, const char * name) : QTextEdit(parent, name)
{
  new CQExpressionHighlighter(this);
}

That’s all !


By Setting Format

Put all the following in a slot called whenever the term ‘<xxx>’ is created. Say, slotText().

void MyHighlighter::slotText(const QString &text)
{
  QTextCharFormat f1 = currentCharFormat();

  QTextCharFormat f2;
  f2.setForeground(Qt::red);

  setCurrentCharFormat(f2);
  insertPlainText("<" + text + ">");
  setCurrentCharFormat(f1);
}

The text format is firstly changed to a specific format for ‘<xxx>’ ( line 8 ) and changed back to the rest ( line 10 ).

That’s all.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>