0
点赞
收藏
分享

微信扫一扫

【github notepad】QT 自动备份,(正则表达式)搜索替换



本文记录使用qt制作一个记事本的一些问题及其解决方案。

基本的记事本编辑操作

相关类:QTextEdit

正则表达式替换

相关类:QRegExp
注:在正则替换时,使用文件流readLine得到的字符串才能用于正则匹配,QTextStream::readAll()和QTextEdit::toPlainText()的得到的字符串消除了​​​^ $​​​。​​.*A$​​​的正则表达式找不到以A结尾的行。
例如:

#include <QCoreApplication>
#include <QRegExp>
#include <QDebug>
#include <QFile>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString path = "/home/edemon/workspace/read";
QFile inputFile(path);
if(!inputFile.open(QIODevice::ReadOnly)){
qDebug()<<"read open failed.";
return 1;
}
QTextStream in(&inputFile);
QString text, newText="";
// ok
text=in.readLine();
while(!text.isEmpty()){
text.replace(QRegExp(".*12$"),"00000");
newText = newText+text+"\n";
text=in.readLine();
}
QFile outFile(path+"1");
if(!outFile.open(QIODevice::WriteOnly)){
qDebug()<<"write open failed.";
return 1;
}
QTextStream out(&outFile);
out<<newText;
outFile.flush();
outFile.close();
// no
// text = in.readAll();
// text.replace(QRegExp(".*12$"),"00000");
// qDebug()<<text;
return

[edemon@CentOS workspace]$ cat read
sdafasd12
cdsaf12
dasgfdagsfdh12
sadfasdgasg

[edemon@CentOS workspace]$ cat read1
00000
00000
00000

普通替换

相关的类和方法
QTextEdit::find();
QTextEdit::textCursor();
QTextEdit::insertText();
QTextEdit::movePosition(QTextCursor::Start);

正则搜索高亮结果显示

继承于 QSyntaxHighlighter的自定义类
主要方法:

void MyHighlighter::highlightBlock(const QString &text)
{
QTextCharFormat myClassFormat;
QColor color(0,0,100,100);
myClassFormat.setBackground(color);
QString pattern = "regular";

QRegExp expression(pattern);
int index = text.indexOf(expression);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, myClassFormat);
index = text.indexOf(expression, index + length);
}
}

貌似:自定义的highlighter只能用指针来声明对象,否则不能渲染。
​​​MyHighlighter *highlighter = new MyHighlighter(textEdit->document());​​​
(持续关注)

普通搜索

QString::indexOf(QString)

void simLighter::highlightBlock(const QString &text)
{
QTextCharFormat myClassFormat;
QColor color(0,0,100,100);
myClassFormat.setBackground(color);
int index = text.indexOf(pattern);
while (index >= 0) {
int length = pattern.length(); //expression.matchedLength();
setFormat(index, length, myClassFormat);
index = text.indexOf(pattern, index + length);
}
}

当前的文本备份

QTimer设定备份周期。
用QFIle,QTextStream 等类将文本写入磁盘。

多标签

利用QTabWidget类,tab的index是从0开始的。

代码设计Action的快捷键

  1. 找按键表
    ​​​New->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N)); // 0x04000000 + 0x4e​
  2. 字符串转换
    ​​​New->setShortcut(QKeySequence(tr("Ctrl+N")));​

文件备份与恢复gif


文本查找gif



正则替换gif


源码地址:​​https://github.com/theArcticOcean/notepad​​


举报

相关推荐

0 条评论