vericule
vericule

Reputation: 285

Changing selection color using QTextCharFormat

I am writing simple editor, I use QTextEdit for text edit QSyntaxHighlighter to do syntax colouring. Style is aplied by QTextCharFormat.

I know how to create simple styles like:

keyword_format = QtGui.QTextCharFormat()
keyword_format.setForeground(QtCore.Qt.darkMagenta)
keyword_format.setFontWeight(QtGui.QFont.Bold)

exception_format = QtGui.QTextCharFormat()
exception_format.setForeground(QtCore.Qt.darkBlue)
exception_format.setFontWeight(QtGui.QFont.Italic)

but how can I change color when text is selected and:

  1. selected text may contain many differently formatted tokens
  2. I might want set selection background color and font color for each formatter independently

I don't know if I explained it enough clearly e.g. I have code

 if foobar:
     return foobar:
 else:
     raise Exception('foobar not set')

Now, if, else, return and raise are keywords and are formatted using keyword_format, Exception is formatted using exception_format. If I select text raise Exception('foobar not set') I would like to change raise keyword, say to green, Exception to pink and leave rest of selection as it is.

Upvotes: 5

Views: 2760

Answers (1)

Akasha
Akasha

Reputation: 235

You can use mergeCharFormat() in conjunction with a QTextCursor pointing at the document() inside the QTextEdit

Usage (C++):

QTextCursor cursor(qTextEditWidget->document());

QTextCharFormat backgrounder;
backgrounder.setBackground(Qt::black);
QTextCharFormat foregrounder;
foregrounder.setForeground(Qt::yellow);

// Apply the background
cursor.setPosition(start, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
cursor.setCharFormat(backgrounder);

cursor.setPosition(start, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);

// Merge the Foreground without overwriting the background
cursor.mergeCharFormat(foregrounder);

It seems to work even if the cursor was moved before merging the second QTextCharFormat

Upvotes: 2

Related Questions