c++ - 在 QTextEdit 中对齐文本?

标签 c++ qt text-alignment qtextedit

如果我有一个 QTextEdit 框,我怎样才能以不同的方式对齐框中的不同文本片段?例如,我想让一个句子左对齐,而框中的下一个句子右对齐。这可能吗?如果没有,我如何在 Qt 中实现这种效果?

最佳答案

正如文档所说:

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

将当前段落的对齐方式设置为a。有效的对齐方式是 Qt::AlignLeftQt::AlignRightQt::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);

我在计算机上得到了哪个结果?

enter image description here

或者更接近您的问题:

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);

结果:

enter image description here

关于c++ - 在 QTextEdit 中对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855024/

相关文章:

html - 如何在 HTML/CSS 中将文本字段与其标题对齐

c++ - QProcess未知错误

qt - wkhtmltopdf 修补了qt?

c++ - 预处理器是否盲目地替换了定义?

用于网络排名和搜索引擎的 C++ 库

c++ - Qt:如何将小部件放置在具有最小宽度和基于百分比的比例的布局中

css - Javascript 有没有办法确定换行符在 HTML 中的位置?

ios6 - NSTextAlignment对齐到iOS6上的UILabel文本对齐方式将崩溃

C++ 静态库 : implement definitions in wrappers/bridges toward native mobile methods (Java, Objective-C)

c++ - boost deadline_timer 不等待