QTextCursor / replace selected text
Can some one explain what I am doing wrong here ?. What I need is to select a text in QTextEdit and make some changes in the selected block texts.
debug prints selected block texts just fine but only when I remove "cursor.insertText("replace block text");". Once added back it screwing up somehow the block numbers and the entire concept. How to do it right ?
Code:
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
if(!cursor.hasSelection())
return;
int startLine = cursor.blockNumber();
int lastLine = cursor.blockNumber();
qDebug() << start << end;
for(int blockNUmber = startLine; blockNUmber <= lastLine; blockNUmber++)
{
QTextBlock block
= document
()->findBlockByNumber
(blockNUmber
);
qDebug() << blockNUmber << block.position() << blockText;
cursor.clearSelection();
cursor.
setPosition(block.
position(),
QTextCursor::KeepAnchor);
cursor.insertText("replace block text");
}
Re: QTextCursor / replace selected text
First you are iterating over blocks in textdocument. So wouldn't this piece of documentation on QTextBlock should be taken care of?
Quote:
The next() and previous() functions enable iteration over consecutive valid blocks in a document under the condition that the document is not modified by other means during the iteration process. Note that, although blocks are returned in sequence, adjacent blocks may come from different places in the document structure. The validity of a block can be determined by calling isValid().
Re: QTextCursor / replace selected text
Thanks. I made some changes. In the example below the text is modified only in the first block. And again removing line cursor.intertText() fixes iteration.
What is wrong yet ? Appreciate for help !
Code:
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
if(!cursor.hasSelection())
return;
for(; block.isValid() && !(endBlock < block); block = block.next())
{
if (!block.isValid())
continue;
qDebug() << block.blockNumber() << block.position() << block.text();
cursor.clearSelection();
cursor.
setPosition(block.
position() ,
QTextCursor::KeepAnchor);
cursor.insertText("replace block text");
}
Re: QTextCursor / replace selected text
I found the problem. QTextCursor::setPosition() is not actually block position, so that was the issue. Best to operate using QTextCursor::movePosition()
Code:
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
if(!cursor.hasSelection())
return;
for(; block.isValid() && !(endBlock < block); block = block.next())
{
if (!block.isValid())
continue;
cursor.clearSelection();
cursor.insertText(" text ");
}