段间距比较容易实现,通过设置html的css即可实现段间距调整;
行间距需要利用Qt用的几个类配合实现;
代码比较简单具体实现如下:
QString HD = ui->H1Edit->text();//行间距
QString HH = ui->H2Edit->text();//段间距
QString src = ui->textEdit->toHtml();
QString strView;
//=ui->textEdit->toPlainText();
strView = "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\np, li { white-space: pre-wrap; }\n</style></head><body style=\" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;\"></body></html>";
int pos = 0;
//padding-top
//获取段落
int startNum = src.indexOf("<p",0);
int endNum = src.lastIndexOf("</body>");
QString txt = src.mid(startNum,endNum);
//更改段间距
const QString StrHH = "margin-top:";
pos = 0;
for(;;)//已知bug 段距大于10
{
pos = txt.indexOf(StrHH,pos+1);
if(pos!=-1)
{
txt.replace(pos+StrHH.length(),1,HH);
}else
{
break;
}
}
int despos = strView.lastIndexOf("</body>");
strView.insert(despos,txt);
ui->textEdit->clear();
ui->textEdit->setHtml(strView);
QTextDocument *doc = ui->textEdit->document();
QTextCursor textcursor = ui->textEdit->textCursor();
for(QTextBlock it = doc->begin(); it !=doc->end();it = it.next())
{
QTextBlockFormat tbf = it.blockFormat();
tbf.setLineHeight(HD.toInt(),QTextBlockFormat::LineDistanceHeight);
textcursor.setPosition(it.position());
textcursor.setBlockFormat(tbf);
ui->textEdit->setTextCursor(textcursor);
}
其中段间距有bug是设置插入字符串位置的问题。需要用的自行解决。