我正在写一个简单的编辑器,我用QTextEdit来编辑文本,用QSyntaxHighlighter来做语法着色。样式是由QTextCharFormat提供的。
我知道如何创建简单的样式,比如。
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)
但当文本被选中时,我怎样才能改变颜色呢?
我不知道我是否解释得够清楚,例如:我的代码为
if foobar:
return foobar:
else:
raise Exception('foobar not set')
现在就去 if
, else
, return
和 raise
是关键词,使用 keyword_format
, Exception
的格式化,使用 exception_format
. 如果我选择文本 raise Exception('foobar not set')
我想改变 raise
关键词,说到绿。Exception
为粉红色,其余部分保持原样。
你可以使用 mergeCharFormat() 与QTextCursor一起指向QTextEdit内部的document()。
使用方法(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);
即使在合并第二个QTextCharFormat之前移动光标,它似乎也能工作。