【问题标题】:How to change current line format in QTextEdit without selection?如何在不选择的情况下更改 QTextEdit 中的当前行格式?
【发布时间】:2011-03-25 21:42:13
【问题描述】:

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

在我读到的文件中

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

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

这是我的代码:

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(); 之后,但它仍然不起作用。事实上,添加这个之后,整个块就变得不可见了。

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

【问题讨论】:

    标签: c++ qt qtextedit


    【解决方案1】:

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

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

    希望这会有所帮助,问候

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多