Qt富文本处理

Qt 富文本处理 无 阅读详情
转自:http://blog.youkuaiyun.com/psujtfc/article/details/37900757

1. Qt对富文本的处理

1.1 操作方式

编辑操作:使用基于光标的接口函数,模拟用户的编辑操作,且不丢失底层文档框架;文档的光标基于QTextCursor类

只读操作:使用了只读的分层次接口函数,有利于文档的检索和输出;文档的框架基于QTextDocument

1.2 富文本文档的结构

结构元素:框架(QTextFrame),文本块(QTextBlock),表格(QTextTable),列表(QTextList)

对应格式:框架格式(QTextFrameFormat),文本块格式(QTextBlockFormat),表格格式(QTextTableFormat),列表格式(QTextListFrame)

格式是在编辑文档时与QTextCursor配合使用

1.3QTextEdit是一个富文本编辑器,在构建QTextEdit对象时就已经构建了一个QTextDocument对象和一个QTextCursor对象

空文档:包含根框架(rootFrame),文本块(Block)


    QTextDocument *doc = ui->textEdit->document(); //获取文档对象
    QTextFrame *rootFrame = doc->rootFrame();   //获取根框架
    QTextFrameFormat frameFormat;           //创建框架格式
    frameFormat.setBorderBrush(Qt::red);    //设置边界颜色
    frameFormat.setBorder(5);       //设置边界宽度
    rootFrame->setFrameFormat(frameFormat); //给框架使用格式



    QTextFrameFormat frameFormat2;	
    frameFormat2.setBackground(Qt::lightGray);	//设置背景色
    frameFormat2.setMargin(10);		//设置边距
    frameFormat2.setPadding(5);		//设置填充
    frameFormat2.setBorder(2);
    frameFormat2.setBorderStyle(QTextFrameFormat::BorderStyle_Dotted);	//设置边框样式
    QTextCursor cursor = ui->textEdit->textCursor();	//获取光标
    cursor.insertFrame(frameFormat2);		//在光标处插入框架
1.4 文本块(QTextBlock)

1.4.1遍历文档框架

1.4.1.1 添加槽函数(在主界面头文件中添加)

private slots:
    void showTextFrame();   //遍历文档框架
1.4.1.2 在工具栏上添加Action

    QAction * act = new QAction(QString("框架"),this);
    connect(act,SIGNAL(triggered()),this,SLOT(showTextFrame()));
    ui->mainToolBar->addAction(act);
1.4.1.3 添加槽函数的实现代码

void MainWindow::showTextFrame()
{
    QTextDocument * doc = ui->textEdit->document();
    QTextFrame *frame = doc->rootFrame();
    QTextFrame::iterator it;                            //建立QTextFrame类的迭代器
    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();

    }
}

1.4.2 遍历文本块

1.4.2.1 添加槽函数(在主界面头文件中添加)

void showTextBlock();   //遍历所有文本块

1.4.2.2 在工具栏上添加Action

    QAction * act_textBlock = new QAction(QString("文本块"),this);
    connect(act_textBlock,SIGNAL(triggered()),this,SLOT(showTextBlock()));
    ui->mainToolBar->addAction(act_textBlock);

1.4.2.3 添加槽函数的实现代码

void MainWindow::showTextBlock()
{
    QTextDocument* doc = ui->textEdit->document();
    QTextBlock block = doc->firstBlock();   //获取文档的第一个文本块
    for(int i = 0; i < doc->blockCount();i++) {
        qDebug() << QString("文本块%1,文本块首行行号为:%2,长度为:%3,内容为:")
                    .arg(i).arg(block.firstLineNumber()).arg(block.length())
                 << block.text();
        block = block.next();
    }
}
1.4.3 设置字体格式

1.4.3.1 添加槽函数(在主界面头文件中添加)

void setTextFont(bool checked); //设置字体格式

1.4.3.2 在工具栏上添加Action

    //设置字体
    QAction * act_font = new QAction(QString("字体"),this);
    act_font->setCheckable(true);
    connect(act_font,SIGNAL(toggled(bool)),this,SLOT(setTextFont(bool)));
    ui->mainToolBar->addAction(act_font);

1.4.3.3 添加槽函数的实现代码

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);

        //宋体,12号,加粗,倾斜
        charFormat.setFont(QFont(QString("宋体"),12,QFont::Bold,true));
        charFormat.setFontUnderline(true);
        cursor.setCharFormat(charFormat);
        cursor.insertText(QString("测试字体"));
    }
}

1.4.4 插入表格,列表,图片

1.4.4.1 添加槽函数(在主界面头文件中添加)

    void insertTable();     //插入表格
    void insertList();      //插入列表
    void insertImage();     //插入图片

1.4.4.2 在工具栏上添加Action

    //插入表格
    QAction * act_insertTable = new QAction(QString("插入表格"),this);
    connect(act_insertTable,SIGNAL(triggered()),this,SLOT(insertTable()));
    ui->mainToolBar->addAction(act_insertTable);
    //插入列表
    QAction * act_insertList = new QAction(QString("插入列表"),this);
    connect(act_insertList,SIGNAL(triggered()),this,SLOT(insertList()));
    ui->mainToolBar->addAction(act_insertList);
    //插入图片
    QAction * act_insertImage = new QAction(QString("插入图片"),this);
    connect(act_insertImage,SIGNAL(triggered()),this,SLOT(insertImage()));
    ui->mainToolBar->addAction(act_insertImage);

1.4.4.3 添加槽函数的实现代码

void MainWindow::insertTable()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextTableFormat tableFormat;
    tableFormat.setCellPadding(10);
    tableFormat.setCellSpacing(2);
    cursor.insertTable(2,2,tableFormat);
}

void MainWindow::insertList()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextListFormat listFormat;
    listFormat.setStyle(QTextListFormat::ListDecimal);
    cursor.insertList(listFormat);
}

void MainWindow::insertImage()
{
    QTextImageFormat imageFormat;
    imageFormat.setName(":/image/2.jpg");
    ui->textEdit->textCursor().insertImage(imageFormat);
}

1.4.5 查找

1.4.5.1 前置声明QLineEdit,在界面头文件中前置声明

class QLineEdit;
1.4.5.2 添加私有对象,前置声明就是为了这里使用的

    QLineEdit *lineEdit;

1.4.5.3 添加私有槽函数

    void textFind();        //文本查找
    void findNext();        //查找下一个
1.4.5.4 添加action

    //查找
    QAction *act_find = new QAction(QString("查找"),this);
    connect(act_find,SIGNAL(triggered()),this,SLOT(textFind()));
    ui->mainToolBar->addAction(act_find);

1.4.5.5 实现槽函数

void MainWindow::textFind() //查找文本
{
    QDialog *dlg = new QDialog(this);       //创建查找对话框
    lineEdit = new QLineEdit(dlg);          //创建字符串输入框
    QPushButton* btFindNext = new QPushButton(this);    //查找按钮
    btFindNext->setText(QString("查找下一个"));

    connect(btFindNext,SIGNAL(clicked()),this,SLOT(findNext())); //关联查找信号和槽
    QVBoxLayout* layout = new QVBoxLayout;      //垂直布局
    layout->addWidget(lineEdit);                //将控件添加到主界面
    layout->addWidget(btFindNext);
    dlg->setLayout(layout);
    dlg->show();
}

void MainWindow::findNext()
{
    QString string = lineEdit->text();
    //查找字符串,查找标志:QTextDocument::FindBackward:向前查找,
    //FindWholeWords:整个文档查找,FindCaseSensitively:忽略大小写查找
    bool isFind = ui->textEdit->find(string,QTextDocument::FindWholeWords);
    if (isFind) {
        qDebug() << QString("行号:%1,列号:%2").arg(ui->textEdit->textCursor().blockNumber())
                    .arg(ui->textEdit->textCursor().columnNumber());
    }
}

1.4.6语法高亮与html

1.4.6.1添加新的文件,选择C++ 类,类名:mySyntaxHighlighter,基类:QSyntaxHighlighter,继承自:QObject

1.4.6.2 修改mysyntaxhighlighter.h头文件

将QTextDocument类对象指针作为其父部件指针,这样可以自动调用highlightBlock()函数,可以时的检测文本

    //将QTextDocument作为父窗口这样就可以自动调用highlightBlock()函数
    explicit mySyntaxHighlighter(QTextDocument *parent = 0);
 重新实现highlightBlock()函数以便将,字符串的格式应用到特定的字符串上面

protected :
    void highlightBlock(const QString &text);   //必须重新实现该函数
1.4.6.3  修改mysyntaxhighlighter.cpp文件

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

void mySyntaxHighlighter::highlightBlock(const QString &text)
{
    QTextCharFormat charFormat;         //设置匹配的字符格式
    charFormat.setFontWeight(QFont::Bold);
    charFormat.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,charFormat);         //对要匹配的字符串设置格式
        index = text.indexOf(expression,index + length); //继续匹配
    }
}

1.4.6.4  修该主界面头文件

    class mySyntaxHighlighter;

添加私有变量

    mySyntaxHighlighter *highlighter;
1.4.6.5 修该主界面的cpp文件

在构造函数中添加

    highlighter = new mySyntaxHighlighter(ui->textEdit->document());

1.4.7 QTextEdit的使用

1.4.7.1 建立一个QTextEdit

    QTextDocument *m_doc = new QTextDocument("文本框中的文本");//创建一个装文本的容器
	QTextEdit te;//定义文本框
	te.setDocument(m_doc);//为文本框绑定内容

1.4.7.2 向QTextEdit中写入数据

    QString gyyq = rec.value("gy").toString();
    te.document()->setPlainText(gyyq);


1.4.7.3 从QTextEdit中读取数据

    QString gyyq = te.document()->toPlainText();










版权声明:本文为博主原创文章,未经博主允许不得转载。

转自:http://blog.youkuaiyun.com/psujtfc/article/details/37900757

QT--富文本处理 富文本处理 富文本文档结构 文本块 表格、列表与图片. 查找功能 语法高亮与HTML 阅读详情

相关推荐

【QT开发】文本块QTextBlock类详解及实战应用

QTextBlock 是 Qt 提供的一个功能强大且灵活的文本块类,通过本篇文章的学习,你应该对 QTextBlock 有了全面的理解,能够在自己的项目中正确使用它。QTextBlock 在用户界面中帮助你更好地管理和操作文本文档的段落,实现复杂的文本处理和显示,有助于创建用户友好和高效的文本编辑器、文本文档查看器等应用场景。

科技改变人类,技术成就未来 1566

【Qt】富文本框架(一、富文本文档)

表是一种特殊类型的框架,它由许多单元格组成,排列成行和列,每个单元格都可以包含进一步的结构和文本。可以将其他文档元素组合在一起的元素通常是qtexttobject的子类,分为两类:将文本块组合在一起的元素是QTextBlockGroup的子类,将框架和其他元素组合在一起的元素是QTextFrame的子类。块也用于表示列表项。因此,块可以定义自己的字符格式,其中包含关于块级装饰的信息,例如用于列表项的项目符号类型。每个表格单元格都是一个文档元素,具有自己的字符格式,但它也可以包含其他元素,如框架和文本块。

卡钦斯基的博客 1943

【QT开发】文本块管理QTextBlock类详解及实战应用

QTextBlock 是 Qt 文本处理框架中的一个重要类,用于访问和操作文档中的文本块。通过本文的学习,您应该对 QTextBlock 的基本使用、高级应用技巧及相关注意事项有了全面的理解。在实际项目中,QTextBlock 可以帮助实现对文档段落的有效管理和操控,希望本文能帮助您更好地理解和使用 QTextBlock,在各种文本处理场景中实现高效的文本块管理。

科技改变人类,技术成就未来 572

第五章 应用程序主窗口——Qt

一、主窗口框架 1.菜单栏和工具栏 (1)菜单栏 ①Qt提供与菜单相关的类组件 见图1(图1.png) ②QMenuBar类、QMenu类和QAction类    ●QMenuBar:QMenuBar类提供了一个水平的菜单栏,可以在此基础上添加不同的QMenu和QAction。一个主窗口只可以有一个菜单栏。    ●QMenu:菜单栏里面菜单(如File、Edit、Format等菜单)或者带有三角形符号的菜单项(表示其下仍有子菜单),可以显示文本和图标, 但是并不负责执行操作,有点类似labe

xiaobai06的博客 2003

CUBEMX ADC 单/多通道+DMA

本文使用的是STM3F103C8T6 Cubemx进行单/多通道DMA配置。

记录学习 1403

Unity UI适配实战:从Canvas Scaler到主流游戏适配方案解析

本文深入解析Unity UI适配的核心技术,重点介绍Canvas Scaler组件的关键参数如Reference Resolution和Screen Match Mode,并提供主流游戏适配方案实战分析。通过九宫格拉伸、动态调整等技巧,帮助开发者解决多设备适配难题,提升游戏UI在不同分辨率下的表现。

weixin_29001419的博客 970

【Qt开发流程】之富文本处理

【Qt开发流程】之富文本处理

FreeLikeTheWind的博客 1944

r语言svr模型_R语言初探强化学习中的马尔可夫模型

强化学习大家这几年应该不陌生,从AlphaGo到AlphaZero让大家见识到了强化学习的力量。我们今天给大家介绍一个在强化学习中核心思维马尔可夫决策过程(MDP)。马尔科夫决策过程是基于马尔科夫论的随机动态系统的最优决策过程。它是马尔科夫过程与确定性的动态规划相结合的产物,故又称马尔科夫型随机动态规划,属于运筹学中数学规划的一个分支。今天我们给大家介绍下马尔可夫决策过程中用到一些算法以...

weixin_28994357的博客 1111

【Qt】富文本处理简单介绍

Qt富文本处理简单介绍

sinat_41752325的博客 2326

从论文到生产:iSLIP优先级匹配算法在SDN交换机中的20年演进史

本文回顾了iSLIP优先级匹配算法在SDN交换机中的20年演进历程,从斯坦福大学的原始论文到现代芯片实现。通过独特的指针滑动和迭代循环机制,iSLIP算法显著提升了交换机的吞吐量和公平性,解决了传统FIFO调度的队头阻塞问题。文章详细探讨了算法在硬件实现中的工程挑战、开源实践及未来AI时代的智能调度方向。

weixin_29230649的博客 331

基于RK3562J开发板的MCP2518FD CAN-FD控制器驱动适配与测试指南

本文详细介绍了在RK3562J开发板上适配MCP2518FD CAN-FD控制器驱动的完整流程。内容涵盖内核驱动配置、设备树修改、编译烧录以及实际通信测试,重点分享了调试方法,旨在帮助开发者快速为嵌入式系统扩展高速CAN-FD通信能力,适用于汽车电子、工业控制等场景。

jenkins8butler的博客 495

Qt开发技术:Qt富文本(二)Qt文本光标操作、文档布局、富文本编辑、处理和Demo

若该文为原创文章,未经允许不得转载 原博主博客地址:https://blog.youkuaiyun.com/qq21497936 原博主博客导航:https://blog.youkuaiyun.com/qq21497936/article/details/102478062 本文章博客地址: 各位读者,知识无穷而人力有穷,要么改需求,要么找专业人士,要么自己研究 目录 前话 文本光标接口 概述 基于光标的编辑 ...

长沙红胖子 Qt・西安|省级科研团队从业背景,深耕双一流体系高精尖技术配套研发|剥离高精尖机理,沉淀高端特种行业领域 Qt 工程化落地经验|博文仅分享通用技术总结,输出公开普适工程思路。 1万+

Linux Kernel入门到精通系列讲解 - 总目录

在学习Linux Kernel之前,需要先准备开发环境,方便后续进行开发。可以根据自身情况,选择性阅读该章节。学习该章节之前,你应该了解一下网络概念,明白为什么要讲这些,才能更有方向的去理解学习。Linux ARM平台开发系列讲解(设备树篇) 4.1.1 设备树的原理详解。本项目完全开源,仅供学习使用,如需其他用途,请与本人联系。),本章节你可以学习到。摄像头V4L2子系统、Linux kernel常用的子系统等,ARM架构、RISCV架构、Uboot等。

DSMGUOGUO的博客 1万+

Qt 富文本处理(01):大纲

文章目录前言用于富文本处理的API用于富文本编辑的控件官方示例总结 前言   Qt的富文本处理使用了Scribe框架,提供一组用于读取和操作结构化富文本文档(RTF)的类。 与以前的Qt支持富文本不同,新类围绕QTextDocument类而不是原始文本信息。 这使开发人员无需创建中间标记格式的内容就可以创建和修改结构化的RTF文档。  Qt 使用QTextDocument 类来存储RTF,使用 QTextCursor 类来编辑RTF, Qt中对富文本的处理分为 编辑 操作和 只读 操作两种方式 : 编辑

读书笔记 1605

【即插即用模块】注意力篇 | TGRS 2025 | SPR:显著性比例协调,注意力聚焦,先抓差异再精准特征融合!

本文提出SPRMamba网络中的显著性比例协调模块(SPR),用于解决遥感变化检测中非显著变化区域的识别难题。该模块通过差异提取→显著性识别→比例融合的三步流程,动态平衡显著与非显著特征表示。SPR包含空间滤波(SF)和上下文记忆(CMM)两个子模块,分别基于统计特征和深度学习自动区分特征差异中的显著性成分。实验表明,SPR能有效抑制背景噪声干扰,提升边缘检测精度,且随着模块数量的增加,模型性能持续改善。该模块计算成本低,可直接嵌入双输入特征融合场景,适用于各类需要动态特征平衡的视觉任务。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 364

R语言中的混淆矩阵(Confusion Matrix)是一种常用的评估多分类模型性能的工具

除了准确率,混淆矩阵还提供了其他有用的指标,如灵敏度(Sensitivity)、特异度(Specificity)、精确度(Precision)和召回率(Recall)。混淆矩阵通过比较模型预测结果与实际标签的一致性,帮助我们了解模型的分类准确性和错误类型。此外,混淆矩阵还提供了各种错误类型的统计信息,如假阳性(False Positive)和假阴性(False Negative)等。通过混淆矩阵,我们可以了解模型的整体性能和错误类型,从而对模型进行评估和改进。最后,为了更好地理解混淆矩阵的结果,可以使用。

HackSquad的博客 972

QT应用主窗口——富文本处理

QTextEdit支持富文本的处理,什么是富文本呢?富文本或者叫做富文本格式,简单来说就是在文档中可以使用多种格式,比如字体颜色,图片和表格等等。它是与纯文本相对而言的,比如Windows上的记事本就是纯文本编辑器,而Word就是富文本编辑器,Qt中提供了对富文本处理的支持,可以在帮助中通过RichTextProcessing关键字查看,哪里详细讲解了富文本处理的相关内容,如果想进一步了解富文本可以在QT中用帮助去学习。Qt对富文本的处理分为编辑操作和只读操作两种方式。

m0_61886762的博客 2485

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Qt 富文本处理(一)

Qt 富文本处理(一) 原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处、作者信息和本声明。否则将追究法律责任。http://devbean.blog.51cto.com/448512/442632 最近使用 Qt 做一个离线博客编辑器,因而用到了 Qt 的富文本处理。参考 Qt 的文档,记录下 Qt 的富文本处理的相关技术。文档地址是http://...

172

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Qt 富文本处理(二)

Qt 富文本处理(二) 原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处、作者信息和本声明。否则将追究法律责任。http://devbean.blog.51cto.com/448512/447358 文档元素 富文本文档通常包括一些通用的元素,例如段落、框架、表格和列表。这些在 QTextDocument 类中分别使用 QTextBlock,QTe...

193

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Qt 富文本处理(13):图像

文章目录前言QTextImageFormat 类代码示例总结 前言   富文本文档的图像由通过资源机制引用外部图像的文本片段表示。层次结构关系如下: QTextImageFormat 类   QTextImageFormat类提供QTextDocument中图像的格式信息。   QTextDocument 中的图像由通过资源机制引用外部图像的文本片段表示。图像是使用光标界面创建的,以后可以通过更改图像文本片段的字符格式进行修改。   内联图像由具有关联的QTextImageFormat的Unicode值U

读书笔记 1724

Qt富文本处理深度解析报告

摘要 Qt富文本引擎架构与操作 本文深入解析了Qt富文本引擎(Scribe框架)的核心架构与操作方式。 架构设计: QTextDocument作为核心模型,独立于UI控件,采用文档中心的数据结构,支持撤销/重做功能。 采用MVC模式,模型(QTextDocument)、视图(QTextEdit)与控制(QTextCursor)分离,实现多视图同步编辑。 提供分层接口(只读)和光标接口(编辑),分别优化查询与修改性能。 文档结构: 采用层次化对象模型,包括根框架(QTextFrame)、段落(QTextBlo

greenspan的专栏 1120
上一篇: Qt遍历文件夹
下一篇: Qt 去除窗口阴影
鱼公子哟西
博客等级 码龄14年 17粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值