如果我有一个 QTextEdit 框,我怎样才能以不同的方式对齐框中的不同文本片段?例如,我想让一个句子左对齐,而框中的下一个句子右对齐。这可能吗?如果没有,我如何在 Qt 中实现这种效果?
最佳答案
正如文档所说:
void QTextEdit::setAlignment(Qt::Alignment a) [slot]
将当前段落的对齐方式设置为a
。有效的对齐方式是 Qt::AlignLeft
、Qt::AlignRight
、Qt::AlignJustify
和 Qt::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);
我在计算机上得到了哪个结果?
或者更接近您的问题:
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);
结果:
关于c++ - 在 QTextEdit 中对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855024/