赞
踩
我们知道html语言和C语言一样也有一些特殊字符,它们是不能正常显示的,必须经过转义,在网上可以查到如何显示这些字符,如下图所示:
<font color=blue>程序例</font>#include<stdio.h>
然后就文本后缀名改为.html后,用浏览器打开,显示如下:
我们从上图可以发现include后面没有显示,但是当我们在文本中写入:
- <font color=blue>程序例</font>#include<stdio.h>
- 或
- <font color=blue>程序例</font>#include<stdio.h>
我们知道Qt能够支持html语言,但是我在编写可以查询c语言函数(肯定有#include后面<>的特殊字符的显示问题)的时候发现使用上面的方法仍然不能显示特殊字符,后来灵机一动,就决定用全角<>来代替半角<>。这样就不会当成是特殊字符了,就可以正常显示了。半角和全角的转换只需要点击下图中的第3个按钮:
<font color=blue>程序例</font>:<br>#include <span style="color:#ff0000;"><</span>stdio.h <span style="color:#ff0000;">></span><br>#include <span style="color:#ff0000;"><</span> stdlib.h <span style="color:#ff0000;">></span><br>int main(void)<br>
- #include "widget.h"
- #include "ui_widget.h"
-
- #include<QString>
- #include<QRegExp>
- #include<QDebug>
- #include<QLabel>
-
- Widget::Widget(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::Widget)
- {
- ui->setupUi(this);
- QString str="<font color=blue>程序例</font>:<br>#include <stdio.h ><br>#include < stdlib.h ><br>int main(void)<br>";
- ui->label->setText(str); //由于Qt也能识别html格式,而< >是html的特殊字符,因此不处理的话,就会出现显示出错
-
- QRegExp rx("#include (<(.*.h )>)");//正则表达式里的括号是为了获取匹配的内容
- rx.setMinimal(true);//非贪婪模式
-
- int pos=0;//从字符串的开始部分
- for(int i=0;i<str.size();i++)
- {
-
- pos=rx.indexIn(str,0);//得到匹配字符串的位置
- while(pos!=-1)//匹配成功
- {
- str.replace(rx.cap(1),"<"+rx.cap(2)+">");//这里是进行替换,如果不明白rx.cap是什么,可以qDebug显示内容
- pos=rx.indexIn(str,pos+rx.matchedLength());//从当前位置,继续往后进行匹配
- }
- }
-
- ui->label1->setText(str);
- }
-
- Widget::~Widget()
- {
- delete ui;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
程序运行结果如下:
下面放一张查单词软件用到的特殊字符显示和使用正则表达式后的截图:
注意:我使用的平台为QT5,如果转移到Qt4上有错的话,可以反向参考http://qt-project.org/wiki/Transition_from_Qt_4.x_to_Qt5
基于Qt的词典开发系列
原文:http://blog.csdn.net/tengweitw/article/details/38734201
作者:nineheadedbird
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。