Aligning text in QTextEdit?

Kvass picture Kvass · Sep 15, 2014 · Viewed 13.6k times · Source

If I have a QTextEdit box, how can I align different pieces of text within the box in different ways? For example, I would like to have one sentence be aligned-left, and the next sentence in the box be aligned-right. Is this possible? If not, how might I achieve this effect in Qt?

Answer

Kosovan picture Kosovan · Sep 15, 2014

As documentation said:

void QTextEdit::setAlignment(Qt::Alignment a) [slot]

Sets the alignment of the current paragraph to a. Valid alignments are Qt::AlignLeft, Qt::AlignRight, Qt::AlignJustify and Qt::AlignCenter (which centers horizontally).

Link: http://qt-project.org/doc/qt-5/qtextedit.html#setAlignment

So as you can see you should provide some alignment to each paragraph.

Little example:

QTextCursor cursor = ui->textEdit->textCursor();
QTextBlockFormat textBlockFormat = cursor.blockFormat();
textBlockFormat.setAlignment(Qt::AlignRight);//or another alignment
cursor.mergeBlockFormat(textBlockFormat);
ui->textEdit->setTextCursor(cursor);

Which result I get on my computer?

enter image description here

Or something closer to your question:

ui->textEdit->clear();
ui->textEdit->append("example");
ui->textEdit->append("example");
QTextCursor cursor = ui->textEdit->textCursor();
QTextBlockFormat textBlockFormat = cursor.blockFormat();
textBlockFormat.setAlignment(Qt::AlignRight);
cursor.mergeBlockFormat(textBlockFormat);
ui->textEdit->setTextCursor(cursor);

ui->textEdit->append("example");

cursor = ui->textEdit->textCursor();
textBlockFormat = cursor.blockFormat();
textBlockFormat.setAlignment(Qt::AlignCenter);
cursor.mergeBlockFormat(textBlockFormat);
ui->textEdit->setTextCursor(cursor);

Result:

enter image description here