QTextBlockFormat resets by pressing the return key for empty block
-
I am making a rich text editor where each paragraph has a different background depending on its type. I set the background using this code:
QTextCursor cursor(ui->textEdit->textCursor()); QTextBlockFormat block_format = cursor.blockFormat(); block_format.setBackground(Qt::yellow); cursor.setBlockFormat(block_format); ui->textEdit->setTextCursor(cursor);
This works well and sets the expected background for the paragraph. However, when I press enter on an empty block I noticed a weird behavior. Instead of adding a new paragraph after the existing one, the active block (the one where the cursor is set) resets its formatting. When the block is non-empty everything works as expected.
I want to leave the block format for the empty paragraph and add a new block by pressing the return key. What am I missing? -
Hi,
If memory serves well, there was a report on the Qt bug tracker for something similar but when removing all blocks and starting to write again. You should check it.
@SGaist thanks, I tried to find something but no luck.
However, I managed to find a workaround. I installed an event filter for the text widget that is listening for the return key and manually inserts a new block.
If someone is interested in the code:if (event->type() == QEvent::KeyPress && object == ui->textEdit) { QKeyEvent* key = static_cast<QKeyEvent*>(event); if (key->key() == Qt::Key_Return) { QTextCursor cursor = ui->textEdit->textCursor(); cursor.insertBlock(); ui->textEdit->setTextCursor(cursor); return true; } return false; }
-
Hi,
If memory serves well, there was a report on the Qt bug tracker for something similar but when removing all blocks and starting to write again. You should check it.
-
Hi,
If memory serves well, there was a report on the Qt bug tracker for something similar but when removing all blocks and starting to write again. You should check it.
@SGaist thanks, I tried to find something but no luck.
However, I managed to find a workaround. I installed an event filter for the text widget that is listening for the return key and manually inserts a new block.
If someone is interested in the code:if (event->type() == QEvent::KeyPress && object == ui->textEdit) { QKeyEvent* key = static_cast<QKeyEvent*>(event); if (key->key() == Qt::Key_Return) { QTextCursor cursor = ui->textEdit->textCursor(); cursor.insertBlock(); ui->textEdit->setTextCursor(cursor); return true; } return false; }
-