c++ - 如何在没有选择的情况下更改 QTextEdit 中的当前行格式?

标签 c++ qt qtextedit

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

在我读到的文档中

"Formatting can be applied to the current text document using the setCharFormat(), mergeCharFormat(), setBlockFormat() and mergeBlockFormat() functions. If the cursor has no selection, current block format will be changed."

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

这是我的代码:

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() 为假,我只是合并新格式以阻止字符。但这不起作用。

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

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

最佳答案

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

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

希望这对你有帮助,问候

关于c++ - 如何在没有选择的情况下更改 QTextEdit 中的当前行格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5427572/

相关文章:

c++ - 防止 QTextEdit 小部件在有选择时滚动

qt - 在不向撤消堆栈中添加撤消命令的情况下对 QTextEdit 进行更改

c++ - 无锁堆栈与原子

使用 setw 的 C++ 文本格式不适用于 QT QTextEdit

c++ - 从 boost ptime 获取年份

c++ - 愚蠢的 C++ 语法尚未声明

qt - 带有滚动区域和网格布局的 qdialog

c++ - 配置 QTextEdit 的换行以添加缩进

c++ - 在 Qt 中隐藏和重新启动同一个 QApplication 实例

c++ - 冲突的模板定义和 ODR