在Python的QTextEdit中使用格式对齐文本 [英] Aligning text using format in a QTextEdit in Python

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

问题描述

我想在QTextEdit中显示文本.我使用format()函数对齐文本并使它看起来像一个干净的表.尽管在外壳中显示文本时得到了完美的结果,但是文本似乎在QTextEdit中没有对齐,就像字符的宽度变化一样.我主要看到出现字符-"时的区别.

I want to display text in a QTextEdit. I use the format() function to align the text and make it look like a clean table. Although I get a perfect result when displaying the text in the shell, the text doesn't seem to align in the QTextEdit, like if the width of a character varies. I mainly see the difference when the character "-" is present.

>>> first_line = "{:<10} {:<3} - {:<20}".format("1234", "EUR", "Mrs Smith")
>>> second_line = "{:<10} {:<3} - {:<20}".format("-45.62", "GBP", "M Doe")
>>> print first_line, "\n", second_line
1234       EUR - Mrs Smith
-45.62     GBP - M Doe

shell中预期的结果.但是使用QTextEdit时,对齐方式不正确,因为您可以看到"EUR"和"GBP"之间的细微差别.在此示例中并没有很多,但是当我在更多行中使用它时,它看起来确实不正确.

The result as expected in the shell. But with the QTextEdit, the alignment is not right as you can see the slight difference between "EUR" and "GBP". It's not much in this example but when I use it with many more lines, it really doesn't look right.

my_text_edit = QTextEdit()
my_text_edit.append(first_line)
my_text_edit.append(second_line)

我尝试使用QPlainTextEdit并得到了相同的结果.无论如何用QTextEdit/QPlainTextEdit得到我想要的东西?还是我应该使用其他显示小部件(无需编辑,标签可以,但是我喜欢文本编辑的外观)?

I tried to use a QPlainTextEdit and got the same result. Anyway to get what I want with a QTextEdit/QPlainTextEdit ? or should I use another display widget (no editing is recquired, a label would do but I like the look of the text edit) ?

推荐答案

我使用的是没有固定宽度的默认字体,因此不对齐.将字体设置为固定宽度的字体(例如等宽字体")解决了我的问题:

I was using the default font that doesn't have a fixed width, hence the non alignment. Setting the font to a fixed width font like 'monospace' solved my problem :

fixed_font = QFont("monospace")
fixed_font.setStyleHint(QFont.TypeWriter)
my_text_edit.setFont(fixed_font)

如果在系统上未找到等宽字体",我使用"setStyleHint"来指示Qt应该使用哪种字体,"QFont.TypeWriter"指示选择固定间距的字体,以便仍然遵循对齐方式.

I used "setStyleHint" to indicate which kind of font Qt should use if 'monospace' is not found on the system, "QFont.TypeWriter" indicating to choose a fixed pitch font so the alignment is still respected.

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

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