如何改变当前的行格式在QTextEdit没有选择? [英] How to change current line format in QTextEdit without selection?

查看:576
本文介绍了如何改变当前的行格式在QTextEdit没有选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有!我想知道如何改变当前的行格式在QTextEdit?

there! I want to find out how to change current line format in QTextEdit?

在文档中我读到


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

"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."

我的应用程序,当前块中的光标无法更改。我可以错过什么吗?

But in my application, the current block in which cursor is couldn't be changed. May I miss something? Then how could I change current block format which has no selection?

这是我的代码:

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,我只是合并新格式块字符。但这不行。

What I want to do is: change current line's format if there is no selection. So if cursor.hasSelection() is false, I just merge new format to block chars. But this does not work.

我也试过添加setTextCorsor(cursor);后的cursor.endEditBlock();,但它仍然不工作。事实上,添加后,整个块变得不可见。

I also tried add setTextCorsor(cursor); after cursor.endEditBlock();, but it still doesn't work. In fact, after adding this, the whole block becomes invisible.

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

So how could I change current block format which has no selection?

推荐答案

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

Pls, check if an example below would work for you, it should change the current text block format and font.

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

希望这有助于您,

这篇关于如何改变当前的行格式在QTextEdit没有选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆