那里!我想了解如何在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();
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是:如果没有选择,改变当前行的格式.因此,如果cursor.hasSelection()为false,我只是将新格式合并到块字符.但这不起作用.
我也试过添加setTextCorsor(cursor); 在cursor.endEditBlock();之后,但它仍然不起作用.事实上,在添加之后,整个块变得不可见.
那我怎么能改变没有选择的当前块格式呢?
请检查下面的示例是否适合您,它应该更改当前的文本块格式和字体.
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);
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助,问候