富文本简单来说就是在文档中可以使用多种格式,比如字体颜色,图片和表格等。Qt对符文的处理分为编辑操作和只读操作,编辑操作使用基于光标的接口函数。文档的光标主要基于QTextCursor类,而文档的框架主要基于QTextDocument类。一个富文本文档的结构分为几种元素来表示,分别是框架(QTextFrame),文本块(QTextBlock),表格(QTextTable),和列表(QTextList)。每种元素的格式又使用相应的format类来表示。QTextEdit就是一个富文本编辑器,在构件它的对象是就已经构件了一个QTextDocument类对象和一个QTextCursor类对象。
对于文档对象和光标对象基本的操作
QTextDocument *document=textEdit->document();
QTextCursor cursor=textEdit->textCursor();
文本块QTextBlock类为文本文档QTextDocument提供了一个文本片段QTextFragment的容器。一个文本块可以看做一个段落,一个回车换行就表示创建一个新的文本块。文本块格式为QTextBlockFormat,字符格式为QTextCharFormat.
QTextBlock block=document->firstBlock();
for(int i=0;i<document->blockCount();i++){
....
block=block.next();
}
QTextBlockFormat blockFormat;
blockFormat.setAlignment(Qt::AlignCenter);
cursor.insertBlock(blockFormat);
QTextCharFormat charFormat;
charFormat.setBackground(Qt::lightGray);
cursor.setCharFormat(charFormat);
cursor.insertText(..); //只有insertText里面的内容会生效
对于表格和列表,可以使用QTextFrame::iterator来遍历它们。表格对应的是QTextTable类,它的每一个单元格对应QTextTableCell,其格式对应的是QTextTableCellFormat类。对于图片,可以使用QTextImageFormat类,不过只能使用setName()来指定它的路径。
QTextTableFormat format;
format.setCellSpacing(2);
format.setCellPadding(10);
cursor.insertTable(2,2,format); //插入表格
QTextListFormat format;
format.setStyle(QTextListFormat::ListDecimal); //数字列表
cursor.insertList(format); //插入列表
QTextImageFormat format;
format.setName("../picture/1.jpg"); //照片路径
cursor.insertImage(format); //插入照片
在富文本中查找可以使用QTextEdit的find函数,不过更推荐使用QTextDocument的find函数。
bool isfind=textEdit->find(string,QTextDocument::FindBackward); //表示向后查找
//还有FindCaseSensitively表示不区分大小写,
//FindWholeWords表示匹配整个单词
Qt的富文本处理中提供了QSyntaxHighlighter类来实现语法高亮,为了实现这个功能,需要创建QSyntaxHighlighter类的子类,然后重新实现highlightBlock函数。
class MySyntaxHighlighter:public QSyntaxHighlighter
{
Q_OBJECT
public:
explicit MySyntaxHighlighter(QTextDocument *parent=0);
protected:
void highlightBlock(const QString &text);
};
void MySyntaxHighlighter::highlightBlock(const QString text);
{
QTextCharFormat format;
format.setFontWeight(QFont::Bold);
format.setForeground(Qt::green);
QString pattern="\\bchar\\b";
QRegExp expression(pattern);
int index=text.indexOf(expression);
while(index>0){
int length=expression.matchedLength();
setFormat(index,length,format);
index=text.indexOf(expression,index+length);
}
}
每当编辑器中的文本改变是都会调用highlightBlock()函数来设置语法高亮。