Qt QTextEdit设置行间距和段间距

段间距比较容易实现,通过设置html的css即可实现段间距调整;

行间距需要利用Qt用的几个类配合实现;

代码比较简单具体实现如下:

QString HD = ui->H1Edit->text();//行间距
    QString HH = ui->H2Edit->text();//段间距

    QString src = ui->textEdit->toHtml();
    QString strView;
    //=ui->textEdit->toPlainText();

    strView = "";

    int pos = 0;

    //padding-top

    //获取段落
    int startNum = src.indexOf("");

    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("");
    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是设置插入字符串位置的问题。需要用的自行解决。

源码下载

你可能感兴趣的:(Qt学习)