在QTextEdit中对齐文本?

Kva*_*ass 1 c++ qt text-alignment qtextedit

如果我有一个QTextEdit框,我如何以不同的方式在框中对齐不同的文本?例如,我想将一个句子左对齐,并且框中的下一个句子对齐 - 右.这可能吗?如果没有,我怎么能在Qt中实现这个效果?

Che*_*byl 6

正如文件所说:

void QTextEdit::setAlignment(Qt::Alignment a) [slot]
Run Code Online (Sandbox Code Playgroud)

将当前段落的对齐方式设置为a.有效比对是Qt::AlignLeft,Qt::AlignRight,Qt::AlignJustifyQt::AlignCenter(其水平中心).

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

因此,您可以看到您应该为每个段落提供一些对齐方式.

小例子:

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

我在电脑上得到了什么结果?

在此输入图像描述

或者更接近你的问题:

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);
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述