Qt之富文本格式

  mainwindow.h如下:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
   
    class MainWindow;
}

class QLineEdit;
class MySyntaxHighlighter;

class MainWindow : public QMainWindow {
   
    Q_OBJECT
public:
    explicit MainWindow ( QWidget *parent = 0 );
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    QLineEdit *lineEdit;
    MySyntaxHighlighter *highlighter;
private slots:
    void showTextFrame();              /* 遍历文档框架   */
    void showTextBlock();              /* 遍历所有文本块 */
    void setTextFont ( bool checked ); /* 设置字体格式   */
    void insertTable();                /* 插入表格       */
    void insertList();                 /* 插入列表       */
    void insertImage();                /* 插入图片       */
    void textFind();                   /* 查找文本       */
    void findNext();                   /* 查找下一个     */
};

#endif // MAINWINDOW_H

  mysyntaxhighlighter.h如下:

#ifndef MYSYNTAXHIGHLIGHTER_H
#define MYSYNTAXHIGHLIGHTER_H

#include <QSyntaxHighlighter>

class MySyntaxHighlighter : public QSyntaxHighlighter {
   
    Q_OBJECT
public:
    explicit MySyntaxHighlighter ( QTextDocument *parent = 0 );
signals:
public slots:
protected:
    void highlightBlock ( const QString &text ); /* 必须重新实现该函数 */
};

#endif // MYSYNTAXHIGHLIGHTER_H

  mysyntaxhighlighter.cpp如下:

#include "mysyntaxhighlighter.h"

MySyntaxHighlighter::MySyntaxHighlighter ( QTextDocument *parent ) :
    QSyntaxHighlighter ( parent ) {
   
}

void MySyntaxHighlighter::highlightBlock ( const QString &text ) {
    /* 高亮文本块 */
    QTextCharFormat myFormat; /* 字符格式 */
    myFormat.setFontWeight ( QFont::Bold );
    myFormat.setForeground ( Qt::green );
    QString pattern = "\\bchar\\b"; /* 要匹配的字符,这里是“char”单词 */
    QRegExp expression ( pattern ); /* 创建正则表达式 */
    int index = text.indexOf ( expression ); /* 从位置0开始匹配字符串 */

    /* 如果匹配成功,那么返回值为字符串的起始位置,它大于或等于0 */
    while ( index >= 0 ) {
   
        int length = expression.matchedLength(); /* 要匹配字符串的长度 */
        setFormat ( index, length, myFormat ); /* 对要匹配的字符串设置格式 */
        index = text.indexOf ( expression, index + length );
        /* 从前面匹配到的字符串之后继续匹配 */
    }
}

  mainwindow.cpp如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextFrame>
#include <QDebug>
#include 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值