3

那里!我想了解如何在 QTextEdit 中更改当前行格式?

在文件中我读到

“可以使用 setCharFormat()、mergeCharFormat()、setBlockFormat() 和 mergeBlockFormat() 函数将格式应用于当前文本文档。如果光标没有选择,则当前块格式将被更改。

但是在我的应用程序中,无法更改光标所在的当前块。我可以错过什么吗?那我怎么能改变当前没有选择的块格式呢?

这是我的代码:

QTextCursor cursor = this->textCursor();
QTextBlockFormat blockFmt;
blockFmt.setNonBreakableLines(true);
blockFmt.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
QTextCharFormat charFmt;
charFmt.setFont(data->visualFont());
if(!cursor.hasSelection()) {
    cursor.beginEditBlock();
    cursor.setBlockFormat(blockFmt);
    cursor.mergeBlockCharFormat(charFmt);
    QTextBlock block = cursor.block();
    block.setUserData(data);
    cursor.endEditBlock();
}

我想做的是:如果没有选择,请更改当前行的格式。因此,如果 cursor.hasSelection() 为 false,我只需合并新格式以阻止字符。但这不起作用。

我也试过添加 setTextCorsor(cursor); 在 cursor.endEditBlock(); 之后,但它仍然不起作用。事实上,添加这个之后,整个块就变得不可见了。

那么如何更改当前没有选择的块格式呢?

4

1 回答 1

5

请检查下面的示例是否适合您,它应该更改当前的文本块格式和字体。

QTextCursor cursor(myTextEdit->textCursor());

// change block format (will set the yellow background)
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setBackground(QColor("yellow"));
blockFormat.setNonBreakableLines(true);
blockFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
cursor.setBlockFormat(blockFormat);

// change font for current block's fragments
for (QTextBlock::iterator it = cursor.block().begin(); !(it.atEnd()); ++it)
{
    QTextCharFormat charFormat = it.fragment().charFormat();
    charFormat.setFont(QFont("Times", 15, QFont::Bold));

    QTextCursor tempCursor = cursor;
    tempCursor.setPosition(it.fragment().position());
    tempCursor.setPosition(it.fragment().position() + it.fragment().length(), QTextCursor::KeepAnchor);
    tempCursor.setCharFormat(charFormat);
}

希望这会有所帮助,问候

于 2011-03-25T03:55:29.617 回答