12

我想设置 QTextEdit 的行距。

获取这些信息没有问题

QFontMetrics::lineSpacing();

但是如何设置呢?

我尝试使用 StyleSheets,但没有奏效:

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

或者

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

部分解决方案:

好吧,我找到了一个解决方案——不是我想要的方式,但至少它很简单,而且它几乎给出了我想要的行为,足以证明我的概念。

在每条新行上都有一些行距。但是,如果您只是键入直到文本自动换行到新行,则这两行之间不会有行距。此 hack 仅适用于文本块,请参阅代码。

请记住,这是蛮力和丑陋的黑客攻击。但它为您漂亮的 QTextEdit 提供了某种行距。每次文本更改时调用它。

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);
        }
    }
}
4

4 回答 4

4

QFontMetrics 包含(按名称)来自字体文件的静态属性。大写字母“C”的宽度等为 lineSpacing()您提供了设计字体的人编码到字体本身的单间距的自然距离。如果你真的想改变(你不想)......这里讲述的有点复杂的故事:

http://fontforge.sourceforge.net/faq.html#linespace

至于 QTextEdit 中的行间距......它看起来(对我来说)被视为属于 Qt 用于指定文本“布局”的可扩展性模型的事情之一:

http://doc.qt.io/qt-4.8/richtext-layouts.html

您将向 QTextDocument 提供您自己的布局类,而不是使用默认值。有人在这里尝试过,但没有发布他们完成的代码:

http://www.qtcentre.org/threads/4198-QTextEdit-with-custom-space-between-lines

于 2012-04-20T17:26:35.400 回答
1

我知道这是一个老问题,但我今天花了很多时间试图为 PyQt5 5.15.2 解决这个问题。我发布我的解决方案以防它对其他人有用。该解决方案适用于 Python,但应该易于移植。

以下代码将一次性将填充的 QTextEdit 小部件的行高更改为 150%。进一步的编辑将选择当前的块格式,并继续应用它。我发现它对于大型文档来说非常慢。

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)
于 2021-02-07T18:19:08.337 回答
1

将块格式应用于整个文档而不是每一行都有效。

QTextBlockFormat bf = this->textCursor().blockFormat();
bf.setLineHeight(lineSpacing, QTextBlockFormat::LineDistanceHeight) ;
this->textCursor().setBlockFormat(bf);
于 2020-04-30T06:03:47.797 回答
1

我已将Jadzia626的代码翻译成 C++ 并且可以正常工作。以下是有关信息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);
于 2021-08-15T08:41:33.500 回答