3

そこの!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();
}

私がやりたいのは、選択がない場合は現在の行の形式を変更することです。したがって、cursor.hasSelection()がfalseの場合、新しい形式をマージして文字をブロックします。しかし、これは機能しません。

setTextCorsor(cursor);も追加してみました。cursor.endEditBlock();の後ですが、それでも機能しません。実際、これを追加すると、ブロック全体が非表示になります。

では、選択のない現在のブロック形式をどのように変更できますか?

4

1 に答える 1

5

pls、以下の例があなたのために働くかどうかチェックしてください、それは現在のテキストブロックフォーマットとフォントを変えるべきです。

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

これがお役に立てば幸いです

于 2011-03-25T03:55:29.617 に答える