QPlainTextEdit ignores most of the text block formats

538 views Asked by At

I wanted to increase spacing between paragraphs (text blocks) in QPlainTextEdit, to no avail. After experimenting I found that though some format properties (e.g., background color) take effect, others (e.g., margins) are ignored.

I found this bug report, but it mentions only QTextBlockFormat::lineHeight(). In my case, almost all methods of QTextBlockFormat::* are ignored. A minimal example:

#include <QtWidgets>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    QPlainTextEdit te;
    te.setPlainText("block1\nblock2\nblock3");

    QTextCursor cursor = te.textCursor();
    cursor.select(QTextCursor::Document);
    QTextBlockFormat fmt;
    fmt.setBackground(QColor(Qt::yellow));
    fmt.setBottomMargin(600);
    fmt.setIndent(20);
    fmt.setTopMargin(600);
    fmt.setLeftMargin(40);
    cursor.setBlockFormat(fmt);
    te.show();
    return a.exec();
}

Except fmt.setBackground(QColor(Qt::yellow)), others are all ignored. Using Qt 5.10.

1

There are 1 answers

1
TrebledJ On

Don't use QPlainTextEdit for intensive formatting over text. Use its cousin, QTextEdit instead.

Using your code and changing it from QPlainTextEdit to QTextEdit resolved the issue.

FYI, this was also mentioned in the Bug Report you linked. Maybe you missed it or forgot to mention it in your question?

Replacing QPlainTextEdit with QTextEdit shows the expected result.

QTextEdit te;               //  note the change in type
te.setPlainText("block1\nblock2\nblock3");

QTextCursor cursor = te.textCursor();
cursor.select(QTextCursor::Document);
QTextBlockFormat fmt;
fmt.setBackground(QColor(Qt::yellow));
fmt.setBottomMargin(6);     //  let's not overexaggerate anything
fmt.setIndent(1);
fmt.setTopMargin(12);
fmt.setLeftMargin(1);
cursor.setBlockFormat(fmt);

Here's the result of using QPlainTextEdit (on a MacOS).

 Oh no!!!

And here's the result of using QTextEdit (on a MacOS).

 Yay!!!

Note that none of the member functions need to be modified, so that's a plus. Transitioning from QPlainTextEdit to QTextEdit shouldn't be much of a pain.

Further Reading: This other SO post kinda helped. Would also be good to read if you're planning on using more Qt Text Classes.