How to change current line format in QTextEdit without selection?
Asked Answered
D

1

3

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

In the document I read that

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

Here is my code:

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

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.

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?

Deodand answered 25/3, 2011 at 1:25 Comment(0)
N
6

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

hope this helps, regards

Nilotic answered 25/3, 2011 at 3:55 Comment(1)
also you might want to take a look at the QSyntaxHighlighter class (doc.qt.nokia.com/latest/qsyntaxhighlighter.html) could be helpful for what you're trying to doNilotic

© 2022 - 2024 — McMap. All rights reserved.