Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set line spacing in QTextEdit

Tags:

c++

qt

I want to set the line spacing of a QTextEdit.

It's no problem to get that information with

QFontMetrics::lineSpacing();

But how to set that?

I tried with StyleSheets, but that didn't work:

this->setStyleSheet("QTextEdit{ height: 200%; }");

or

this->setStyleSheet("QTextEdit{ line-height: 200%; }");

Partial solution:

Well, I've found a solution - not the way I wanted it, but at least it's simple and it gives nearly my intended behavior, enough for my proof of concept.

On every new line there's some linespacing. But if you just type until the text is automatically wrapped to a new line you wont have line-spacing between this two lines. This hack only works with text blocks, see the code.

Just keep in mind it's brute force and a ugly hack. But it provides some kind of line-spacing to your beautiful QTextEdit. Call it everytime your text changes.

void setLineSpacing(int lineSpacing) {
    int lineCount = 0;
    for (QTextBlock block = this->document()->begin(); block.isValid();
            block = block.next(), ++lineCount) {
        QTextCursor tc = QTextCursor(block);
        QTextBlockFormat fmt = block.blockFormat();
        if (fmt.topMargin() != lineSpacing
                || fmt.bottomMargin() != lineSpacing) {
            fmt.setTopMargin(lineSpacing);
            //fmt.setBottomMargin(lineSpacing);
            tc.setBlockFormat(fmt);
        }
    }
}
like image 604
qwc Avatar asked Apr 20 '12 17:04

qwc


2 Answers

I have translated Jadzia626's code to C++ and it works. Here is the information about setLineHeight()

qreal lineSpacing = 35;
QTextCursor textCursor = ui->textBrowser->textCursor();

QTextBlockFormat * newFormat = new QTextBlockFormat();
textCursor.clearSelection();
textCursor.select(QTextCursor::Document);
newFormat->setLineHeight(lineSpacing, QTextBlockFormat::ProportionalHeight);
textCursor.setBlockFormat(*newFormat);
like image 198
driftingdream Avatar answered Sep 21 '22 09:09

driftingdream


I know this is an old question, but I've spent a lot of time today trying to solve this for PyQt5 5.15.2. I'm posting my solution in case it is useful to others. The solution is for Python, but should be easily transferable.

The following code will change the line height to 150% for a populated QTextEdit widget in one go. Further editing will pick up the current block format, and continue applying it. I've found it to be very slow for large documents though.

textEdit = QTextEdit()

# ... load text into widget here ...

blockFmt = QTextBlockFormat()
blockFmt.setLineHeight(150, QTextBlockFormat.ProportionalHeight)
    
theCursor = textEdit.textCursor()
theCursor.clearSelection()
theCursor.select(QTextCursor.Document)
theCursor.mergeBlockFormat(blockFmt)
like image 20
Jadzia626 Avatar answered Sep 18 '22 09:09

Jadzia626