Qt in Rich Text Processing

Rich Text Processing

 Rich text (Rich Text) or rich text format is called, it is simply a document that can be used in a variety of formats, such as font color, images and tables, and so on. It is a plain text (Plain Text) relative, such as Notepad on Windows this is a plain text editor, but Word is the rich text editor.

  • Rich Text Document
  • Text blocks
  • Tables, lists and images
  • Find feature
  • Syntax highlighting and HTML

1 Rich Text Document

It provides support for rich text processing in Qt. Qt in handling rich text into the editing operation and a read-only operation in two ways.

  • Editing operations are based on a number of interface functions using the cursor, so that better simulates the user's editing operation, easier to understand, but without losing the underlying framework document.
  • For an overview of the structure of the document, use read-only hierarchical interface functions, which facilitate retrieval and output of documents.

For read and edit documents to be used two different aspects of the interface.

  • The cursor is mainly based on the document type QTextCursor
  • Framework document is mainly based on class QTextDocument

A rich text document structure is divided into several elements to represent:

  • Framework (QTextFrame)
  • Text block (QTextBlock)
  • Form (QTextTable)
  • List (QTextList)

 Format each element and the corresponding format type used to represent:

  • Frame format (QTextFrameFormat)
  • Text block format (QTextBlockFormat)
  • Tabular format (QTextTableFormat)
  • List format (QTextListFormat)

These formats usually use when editing a document, and they are often used in conjunction with QTextCursor class.

Because QTextEdit class is a rich text editor, so when building an object QTextEdit class had already built a QTextDocument QTextCursor class object and a class object, simply call them the appropriate action can be.

A blank document contains a root frame (Root frame), the root frame also contains an empty text block (Block). The document is divided into a plurality of frame portions, can add text block, the sub-frame, and tables in the framework of the root. 

  

Set Root frame

. 1 by QTextDocument for * = ui- Document> textEdit-> Document (); // get the document objects 
2   
. 3 QTextFrame rootFrame * = document-> rootFrame ();       // get the root frame 
. 4   
. 5 QTextFrameFormat the format;                             // Create a frame format 
. 6   
. 7 format.setBorderBrush (the Qt :: Red);                      // border color 
. 8   
. 9 format.setBorder ( . 3 );                                 // width of the boundary 
10   
. 11 rootFrame-> setFrameFormat (the format);                   // the frame using the format

Add subframe

 

. 1  QTextFrameFormat frameFormat;
 2   
. 3 frameFormat.setBackground (the Qt :: lightGray);                 // set the background color 
. 4   
. 5 frameFormat.setMargin ( 10 );                                // set margins 
. 6   
. 7 frameFormat.setPadding ( . 5 );                                // set the fill liner 
8   
. 9 frameFormat.setBorder ( 2 );
 10   
. 11  // sets the border style 
12 is  frameFormat.setBorderStyle (QTextFrameFormat :: BorderStyle_Dotted); 
 13 is   
14Cursor = ui- QTextCursor> textEdit-> TextCursor ();          // Get the cursor 
15   
16 cursor.insertFrame (frameFormat);                          // inserted into the frame at the cursor

 

Text block 2

Text block QTextBlock class provides a text segment (QTextFragment) of the container as a text document QTextDocument.

 A text block can be seen as a paragraph, but it can not use the carriage return line feed, because it means a carriage return line to create a new text block. QTextBlock provides a read-only interface, which is part of the document hierarchical interface mentioned earlier, if QTextFrame seen as a layer, then one of QTextBlock is another.

Plaintext block is processed by QTextBlockFormat class, it is primarily directed to alignment, text blocks around the edge of the white, indents content. Format and text content of the text block, such as font size, bold, underline, etc., provided by QTextCharFormat class.

Traverse frame

 

. 1 by QTextDocument for * = ui- Document> textEdit-> Document ();
 2      QTextFrame * Frame = document-> rootFrame ();
 . 3      QTextFrame :: Iterator IT;                        // build QTextFrame iterator class 
. 4      for (Frame-IT => the begin ();! (it.atEnd ()); ++ IT) {
 . 5           QTextFrame * childFrame it.currentFrame = (); // get a pointer to the current frame 
. 6           QTextBlock childBlock it.currentBlock = (); // get the current text blocks 
. 7           IF (childFrame)
 . 8               qDebug () << " Frame " ;
 . 9           the else if (childBlock.isValid())
10              qDebug() << "block:" << childBlock.text();
11     }

 

Traversing the sub-frame

 

1 QTextDocument *document = ui->textEdit->document();
2     QTextBlock block = document->firstBlock();    // 获取文档的第一个文本块
3     for (int i = 0; i < document->blockCount(); i++) {
4         qDebug() << tr("文本块%1,文本块首行行号为:%2,长度为:%3,内容为:")
5                     .arg(i).arg(block.firstLineNumber()).arg(block.length())
6                     << block.text();
7         block = block.next();                         // 获取下一个文本块
8     }

 

 1 QTextCursor cursor = ui->textEdit->textCursor();
 2 QTextBlockFormat blockFormat;      // 文本块格式
 3 blockFormat.setAlignment(Qt::AlignCenter); // 水平居中
 4 cursor.insertBlock(blockFormat);   // 使用文本块格式
 5 QTextCharFormat charFormat;// 字符格式
 6 charFormat.setBackground(Qt::lightGray);   // 背景色
 7 charFormat.setForeground(Qt::blue);// 字体颜色
 8 // 使用宋体,12号,加粗,倾斜
 9 charFormat.setFont(QFont(tr("宋体"), 12, QFont::Bold, true)); 
10 charFormat.setFontUnderline(true); // 使用下划线
11 cursor.setCharFormat(charFormat);  // 使用字符格式
12 cursor.insertText(tr("测试字体")); // 插入文本

3 表格、列表和图片

 

 1 //插入表格   
 2     QTextCursor cursor = ui->textEdit->textCursor();
 3     QTextTableFormat format;          // 表格格式
 4     format.setCellSpacing(2);         // 表格外边白
 5     format.setCellPadding(10);        // 表格内边白
 6     cursor.insertTable(2, 2, format); // 插入2行2列表格
 7 //插入列表
 8    QTextListFormat format;           // 列表格式
 9     format.setStyle(QTextListFormat::ListDecimal);   // 数字编号
10     ui->textEdit->textCursor().insertList(format);
11 //插入图片
12     QTextImageFormat format;          // 图片格式
13     format.setName("logo.png");       // 图片路径
14     ui->textEdit->textCursor().insertImage(format);

 

4 查找功能

 

 1 //查找文本   
 2    QDialog *dlg = new QDialog(this);         // 创建对话框
 3     lineEdit = new QLineEdit(dlg);            // 创建行编辑器
 4     QPushButton *btn = new QPushButton(dlg);  // 创建按钮
 5     btn->setText(tr("查找下一个"));
 6     connect(btn,SIGNAL(clicked()),this,SLOT(findNext())); // 关联信号和槽
 7     QVBoxLayout *layout = new QVBoxLayout;    // 创建垂直布局管理器
 8     layout->addWidget(lineEdit);              // 添加部件
 9     layout->addWidget(btn);
10     dlg->setLayout(layout);                   // 在对话框中使用布局管理器
11     dlg->show();
12  
13 //查找下一个
14    QString string = lineEdit->text();
15     // 使用查找函数查找指定字符串,查找方式为向后查找
16     bool isfind = ui->textEdit->find(string, QTextDocument::FindBackward);
17     if(isfind){                // 如果查找成功,输出字符串所在行和列的编号
18         qDebug() << tr("行号:%1 列号:%2")
19                     .arg(ui->textEdit->textCursor().blockNumber())
20                     .arg(ui->textEdit->textCursor().columnNumber());
21     }

 

5 语法高亮

在使用Qt Creator编辑代码时可以发现,输入关键字时会显示不同的颜色,这就是所谓的语法高亮。

在Qt的富文本处理中提供了QSyntaxHighlighter类来实现语法高亮。为了实现这个功能,需要创建QSyntaxHighlighter类的子类,然后重新实现highlightBlock()函数,使用时直接将QTextDocument类对象指针作为其父部件指针,这样就可以自动调用highlightBlock()函数了。

例如,自定义的类为MySyntaxHighlighter,像这样来使用:      highlighter = new MySyntaxHighlighter(ui->textEdit->document());      这里创建了MySyntaxHighlighter类的对象,并且使用编辑器的文档对象指针作为其参数,这样,每当编辑器中的文本改变时都会调用highlightBlock()函数来设置语法高亮。

重新实现highlightBlock()函数:

 1 QTextCharFormat myFormat;             // 字符格式
 2      myFormat.setFontWeight(QFont::Bold);
 3      myFormat.setForeground(Qt::green);
 4      QString pattern = "\\bchar\\b";       // 要匹配的字符,这里是“char”单词
 5      QRegExp expression(pattern);          // 创建正则表达式
 6      int index = text.indexOf(expression); // 从位置0开始匹配字符串
 7      // 如果匹配成功,那么返回值为字符串的起始位置,它大于或等于0
 8      while (index >= 0) {    
 9          int length = expression.matchedLength(); // 要匹配字符串的长度
10          setFormat(index, length, myFormat);      // 对要匹配的字符串设置格式
11          index = text.indexOf(expression, index + length); // 继续匹配
12      }
13 在这里主要是使用了正则表达式和QString类的indexOf()函数来进行字

在这里主要是使用了正则表达式和QString类的indexOf()函数来进行字符串的匹配,如果匹配成功,则使用QSyntaxHighlighter类的setFormat()函数来设置字符格式。

6 HTML

在富文本处理中还提供了对HTML子集的支持,可以在QLabel或者QTextEdit添加文本时使用HTML标签或者CSS属性,例如:

ui->textEdit->append(tr("<h1><font color=red>使用HTML</font></h1>"));  
 

这里往编辑器中添加了文本,并且使用了HTML标签,

本文链接:https://blog.csdn.net/qq_40732350/article/details/86696217

Guess you like

Origin www.cnblogs.com/mtn007/p/11854549.html