在QTextEdit中对齐文本? [英] Aligning text in QTextEdit?

查看:1124
本文介绍了在QTextEdit中对齐文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

如文档所述:

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

将当前段落的对齐方式设置为 a 。有效的对齐方式是 Qt :: AlignLeft Qt :: AlignRight Qt :: AlignJustify Qt :: AlignCenter (水平居中)。

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

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

因此,如您所见,您应该为每个段落提供一些对齐方式。

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

小示例:

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?

您的问题:

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

结果:

这篇关于在QTextEdit中对齐文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆