Qt - 富文本(富文本编程-语法高亮)

2023-10-31

富文本

QTextEdit支持富文本处理,即文档中可使用多种格式,如文字、图片、表格等。与纯文本PlainText相对而言,windows的记事本就是纯文本编辑器,word就是富文本编辑器。
文档的光标主要基于QTextCursor类,文档的框架主要基于QTextDocument类。
一个富文本的文档结构主要分为几种元素:框架(QTextFrame)、文本块(QTextBlock)、表格(QTextTable)、和列表(QTextList)。
每种元素的格式有相应的format类表示:框架格式(QTextFrameFormat)、文本块格式(QTextBlockFormat)、表格格式(QTextTableFormat)、列表格式(QTextListFormat)。这些格式通常配合QTextCursor类使用。
QTextEdit类就是一个富文本编辑器,在构建QTextEdit类对象时就已经构建了一个QTextDocument类对象和一个QTextCursor类对象。只需调用他们进行相应的操作即可。
在这里插入图片描述

富文本编程-语法高亮

继续上一节的代码

右键点击项目名testRichText,添加C++类,类名MySyntaxHighlighter
,父类QSyntaxHighlighter
编辑MySyntaxHighlighter.h头文件
在这里插入图片描述

==================================================================
MySyntaxHighlighter.cpp编辑构造函数,重写highlighBlock事件
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

具体操作

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

具体代码

未雨绸缪还是给全代码方便以后查找

mainwindow.h

在这里插入图片描述

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "mysyntaxhighlighter.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void showTextFrame();           //遍历文档框架
    void showTextBlock();           //遍历文本块
    void setTextFont(bool checked); //设置文本字体
    void insertTable();             //插入表格
    void insertList();              //插入列表
    void insertImage();             //插入图片

private:
    Ui::MainWindow *ui;
    MySyntaxHighlighter *m_sLighter;
};

#endif // MAINWINDOW_H

mainwindow.cpp

在这里插入图片描述

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextFrame>
#include <QDebug>
#include <QFileDialog>
#include <QImage>
#include <QImageReader>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //获取文档对象
    QTextDocument *document = ui->textEdit->document();

    //获取根框架
    QTextFrame *rootFrame = document->rootFrame();

    //文档框架格式
    QTextFrameFormat format;
    format.setBorderBrush(Qt::red); //边框颜色
    format.setBorder(3);            //边框宽度

    //文档框架设置格式
    rootFrame->setFrameFormat(format);

    //设置文本边框风格
    QTextFrameFormat frameFormat;
    frameFormat.setBackground(Qt::lightGray);
    frameFormat.setMargin(10);  //设置边距
    frameFormat.setPadding(15); //设置填衬
    frameFormat.setBorder(2);
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Dashed);

    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.insertFrame(frameFormat);

    QAction *action_textFrame = new QAction("框架", this);
    connect(action_textFrame, &QAction::triggered, this, &MainWindow::showTextFrame);
    ui->mainToolBar->addAction(action_textFrame);

    QAction *action_textBlock = new QAction("文本块", this);
    connect(action_textBlock, &QAction::triggered, this, &MainWindow::showTextBlock);
    ui->mainToolBar->addAction(action_textBlock);

    QAction *action_textFont = new QAction("字体", this);
    action_textFont->setCheckable(true);
    connect(action_textFont, &QAction::triggered, this, &MainWindow::setTextFont);
    ui->mainToolBar->addAction(action_textFont);


    QAction *action_textTable = new QAction("表格", this);
    QAction *action_textList = new QAction("列表", this);
    QAction *action_textIamge = new QAction("图片", this);
    connect(action_textTable, &QAction::triggered, this, &MainWindow::insertTable);
    connect(action_textList, &QAction::triggered, this, &MainWindow::insertList);
    connect(action_textIamge, &QAction::triggered, this, &MainWindow::insertImage);

    //工具栏添加动作按钮
    ui->mainToolBar->addAction(action_textTable);
    ui->mainToolBar->addAction(action_textList);
    ui->mainToolBar->addAction(action_textIamge);

    m_sLighter = new MySyntaxHighlighter(ui->textEdit->document());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showTextFrame()
{
    //获取文档对象
    QTextDocument *document = ui->textEdit->document();

    //获取根框架
    QTextFrame *frame = document->rootFrame();

    QTextFrame::iterator it;
    for (it = frame->begin(); !(it.atEnd()); ++it)
    {
        //获取当前框架指针
        QTextFrame *childFrame = it.currentFrame();

        //获取当前文本
        QTextBlock childBlock = it.currentBlock();
        if (childFrame)
            qDebug() << "frame";
        else if (childBlock.isValid())
            qDebug() << "block" << childBlock.text();
    }
}

void MainWindow::showTextBlock()
{
    QTextDocument *document = ui->textEdit->document();
    QTextBlock block = document->firstBlock();

    //document->blockCount() 返回文本块个数
    for (int i = 0; i < document->blockCount(); i++)
    {
        //输出文本信息
        qDebug() << QString("文本块: %1, 文本块首行行号:%2, 长度%3, 内容%4")
                    .arg(i)
                    .arg(block.firstLineNumber())
                    .arg(block.length())
                    .arg(block.text());
        block = block.next();
    }
}

void MainWindow::setTextFont(bool checked)
{
    if (checked)
    {
        QTextCursor cursor = ui->textEdit->textCursor();

        //文本块格式
        QTextBlockFormat blockFormat;
        //居中对齐
        blockFormat.setAlignment(Qt::AlignCenter);
        cursor.insertBlock(blockFormat);

        //字符格式
        QTextCharFormat charFormat;
        //字符背景色
        charFormat.setBackground(Qt::lightGray);
        //字符前景色(字符颜色)
        charFormat.setForeground(Qt::blue);
        //字体
        charFormat.setFont(QFont(QString("宋体"), 12, QFont::Bold, true));
        //下划线
        charFormat.setFontUnderline(true);

        //设置字符格式
        cursor.setCharFormat(charFormat);
        cursor.insertText("哈哈哈哈哈");
    }
}

void MainWindow::insertTable()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextTableFormat format;   //表格格式
    format.setCellSpacing(2);  //表格外变白
    format.setCellPadding(10); //表格内边白
    cursor.insertTable(3, 3, format);
}

void MainWindow::insertList()
{
    QTextListFormat format;                        //列表格式
    format.setStyle(QTextListFormat::ListDecimal); //数字编号
    ui->textEdit->textCursor().insertList(format);
}

void MainWindow::insertImage()
{
    QString filepath = QFileDialog::getOpenFileName(this, "选择图片", ".", "JPEG(.jpg *.jpeg);;GIG(*gif);;PNG(*.png)");

    QUrl url(QString("file://%1").arg(filepath));
    QImage image = QImageReader(filepath).read();

    QTextDocument *document = ui->textEdit->document();
    //文档添加图片资源
    document->addResource(QTextDocument::ImageResource, url, QVariant(image));
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextImageFormat imgFormat;
    imgFormat.setWidth(image.width());
    imgFormat.setHeight(image.height());
    imgFormat.setName(url.toString());
    cursor.insertImage(imgFormat);
}

mysyntaxthlighter.h

在这里插入图片描述

#ifndef MYSYNTAXHIGHLIGHTER_H
#define MYSYNTAXHIGHLIGHTER_H
#include <QSyntaxHighlighter>


class MySyntaxHighlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    MySyntaxHighlighter(QTextDocument *parent = 0);

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 format; //字符格式
    format.setFontWeight(QFont::Bold);
    format.setBackground(Qt::red); //背景红色
    format.setForeground(Qt::green); //字体绿色

    QString pattern = "\\bgood\\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));
    }
}

main.cpp

没动过

结语:

时间: 2020-08-12

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Qt - 富文本(富文本编程-语法高亮) 的相关文章

  • 删除文件的最后 10 个字符

    我想删除文件的最后 10 个字符 说一个字符串 hello i am a c learner 是文件内的数据 我只是希望该文件是 hello i am a 文件的最后 10 个字符 即字符串 c learner 应在文件内消除 解决方案 将
  • 如何从 Visual Studio 将视图导航到其控制器?

    问题是解决方案资源管理器上有 29 个项目 而且项目同时具有 ASP NET MVC 和 ASP NET Web 表单结构 在MVC部分中 Controller文件夹中有大约100个子文件夹 每个文件夹至少有3 4个控制器 视图完全位于不同
  • -webkit-box-shadow 与 QtWebKit 模糊?

    当时有什么方法可以实现 webkit box shadow 的工作模糊吗 看完这篇评论错误报告 https bugs webkit org show bug cgi id 23291 我认识到这仍然是一个问题 尽管错误报告被标记为RESOL
  • 如何在 C++ 中标记字符串?

    Java有一个方便的分割方法 String str The quick brown fox String results str split 在 C 中是否有一种简单的方法可以做到这一点 The 增强分词器 http www boost o
  • Qt 支持 Windows 蓝牙 API 吗?

    谁能告诉我 Qt 是否支持 Windows 蓝牙 API 如果是这样 您能否分享一些有关如何使用它的信息 自上次答复以来 这个问题的答案发生了一些变化 Qt 5 2 版为 Linux BlueZ 和 BlackBerry 设备实现了蓝牙 A
  • 需要帮助优化算法 - 两百万以下所有素数的总和

    我正在尝试做一个欧拉计划 http projecteuler net问题 我正在寻找 2 000 000 以下所有素数的总和 这就是我所拥有的 int main int argc char argv unsigned long int su
  • 人脸 API DetectAsync 错误

    我想创建一个简单的程序来使用 Microsoft Azure Face API 和 Visual Studio 2015 检测人脸 遵循 https social technet microsoft com wiki contents ar
  • ASP.NET Core 3.1登录后如何获取用户信息

    我试图在登录 ASP NET Core 3 1 后获取用户信息 如姓名 电子邮件 id 等信息 这是我在登录操作中的代码 var claims new List
  • 使用 C# 中的 CsvHelper 将不同文化的 csv 解析为十进制

    C 中 CsvHelper 解析小数的问题 我创建了一个从 byte 而不是文件获取 csv 文件的类 并且它工作正常 public static List
  • WcfSvcHost 的跨域异常

    对于另一个跨域问题 我深表歉意 我一整天都在与这个问题作斗争 现在已经到了沸腾的地步 我有一个 Silverlight 应用程序项目 SLApp1 一个用于托管 Silverlight SLApp1 Web 的 Web 项目和 WCF 项目
  • 为什么这个字符串用AesCryptoServiceProvider第二次解密时不相等?

    我在 C VS2012 NET 4 5 中的文本加密和解密方面遇到问题 具体来说 当我加密并随后解密字符串时 输出与输入不同 然而 奇怪的是 如果我复制加密的输出并将其硬编码为字符串文字 解密就会起作用 以下代码示例说明了该问题 我究竟做错
  • 如何定义一个可结构化绑定的对象的概念?

    我想定义一个concept可以检测类型是否T can be 结构化绑定 or not template
  • LINQ:使用 INNER JOIN、Group 和 SUM

    我正在尝试使用 LINQ 执行以下 SQL 最接近的是执行交叉联接和总和计算 我知道必须有更好的方法来编写它 所以我向堆栈团队寻求帮助 SELECT T1 Column1 T1 Column2 SUM T3 Column1 AS Amoun
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 复制目录下所有文件

    如何将一个目录中的所有内容复制到另一个目录而不循环遍历每个文件 你不能 两者都不Directory http msdn microsoft com en us library system io directory aspx nor Dir
  • 如何在 Linq to SQL 中使用distinct 和 group by

    我正在尝试将以下 sql 转换为 Linq 2 SQL select groupId count distinct userId from processroundissueinstance group by groupId 这是我的代码
  • 如何在 Android 中使用 C# 生成的 RSA 公钥?

    我想在无法假定 HTTPS 可用的情况下确保 Android 应用程序和 C ASP NET 服务器之间的消息隐私 我想使用 RSA 来加密 Android 设备首次联系服务器时传输的对称密钥 RSA密钥对已在服务器上生成 私钥保存在服务器
  • 对于某些 PDF 文件,LoadIFilter() 返回 -2147467259

    我正在尝试使用 Adob e IFilter 搜索 PDF 文件 我的代码是用 C 编写的 我使用 p invoke 来获取 IFilter 的实例 DllImport query dll SetLastError true CharSet
  • C# 使用“?” if else 语句设置值这叫什么

    嘿 我刚刚看到以下声明 return name null name NA 我只是想知道这在 NET 中叫什么 是吗 代表即然后执行此操作 这是一个俗称的 条件运算符 三元运算符 http en wikipedia org wiki Tern
  • Mono 应用程序在非阻塞套接字发送时冻结

    我在 debian 9 上的 mono 下运行一个服务器应用程序 大约有 1000 2000 个客户端连接 并且应用程序经常冻结 CPU 使用率达到 100 我执行 kill QUIT pid 来获取线程堆栈转储 但它总是卡在这个位置

随机推荐