在 Python 的 QTextEdit 中使用格式对齐文本
Aligning text using format in a QTextEdit in Python
我想在 QTextEdit 中显示文本。我使用 format() 函数来对齐文本并使其看起来像干净的 table。虽然我在 shell 中显示文本时得到了完美的结果,但文本在 QTextEdit 中似乎没有对齐,就像字符的宽度变化一样。我主要是看到字符“-”存在时的区别。
>>> 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" 之间的细微差别。在这个例子中它并不多,但是当我将它与更多行一起使用时,它看起来确实不对。
my_text_edit = QTextEdit()
my_text_edit.append(first_line)
my_text_edit.append(second_line)
我尝试使用 QPlainTextEdit 并得到了相同的结果。无论如何要用 QTextEdit/QPlainTextEdit 得到我想要的东西?或者我应该使用另一个显示小部件(不需要编辑,标签就可以,但我喜欢文本编辑的外观)?
我使用的是没有固定宽度的默认字体,因此没有对齐。将字体设置为 'monospace' 等固定宽度的字体解决了我的问题:
fixed_font = QFont("monospace")
fixed_font.setStyleHint(QFont.TypeWriter)
my_text_edit.setFont(fixed_font)
我用"setStyleHint"表示如果系统上找不到'monospace'Qt应该使用哪种字体,"QFont.TypeWriter"表示选择固定间距的字体所以对齐方式是仍然受到尊重。
我通过使用 Unicode 间距和 python 格式对齐文本或浮点数得到了很好的结果。
示例:
self.mlist.append('{:\u2000<11d}'.format(martnr)+\
'{:\u2000<40s}'.format(momschr)+'\n'+\
'{:\u2000>6d}'.format(int(maantal))+\
'{:\u2000>12.2f}'.format(mprijs)+\
'{:\u2000>12.2f}'.format(float(mprijs)*float(maantal))+\
'{:\u2000>12.2f}'.format(float(mprijs)*float(maantal)*mbtw))
self.view.append(self.mlist[-1])
其中 self.view 是 QTextEdit 视图
我想在 QTextEdit 中显示文本。我使用 format() 函数来对齐文本并使其看起来像干净的 table。虽然我在 shell 中显示文本时得到了完美的结果,但文本在 QTextEdit 中似乎没有对齐,就像字符的宽度变化一样。我主要是看到字符“-”存在时的区别。
>>> 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" 之间的细微差别。在这个例子中它并不多,但是当我将它与更多行一起使用时,它看起来确实不对。
my_text_edit = QTextEdit()
my_text_edit.append(first_line)
my_text_edit.append(second_line)
我尝试使用 QPlainTextEdit 并得到了相同的结果。无论如何要用 QTextEdit/QPlainTextEdit 得到我想要的东西?或者我应该使用另一个显示小部件(不需要编辑,标签就可以,但我喜欢文本编辑的外观)?
我使用的是没有固定宽度的默认字体,因此没有对齐。将字体设置为 'monospace' 等固定宽度的字体解决了我的问题:
fixed_font = QFont("monospace")
fixed_font.setStyleHint(QFont.TypeWriter)
my_text_edit.setFont(fixed_font)
我用"setStyleHint"表示如果系统上找不到'monospace'Qt应该使用哪种字体,"QFont.TypeWriter"表示选择固定间距的字体所以对齐方式是仍然受到尊重。
我通过使用 Unicode 间距和 python 格式对齐文本或浮点数得到了很好的结果。
示例:
self.mlist.append('{:\u2000<11d}'.format(martnr)+\
'{:\u2000<40s}'.format(momschr)+'\n'+\
'{:\u2000>6d}'.format(int(maantal))+\
'{:\u2000>12.2f}'.format(mprijs)+\
'{:\u2000>12.2f}'.format(float(mprijs)*float(maantal))+\
'{:\u2000>12.2f}'.format(float(mprijs)*float(maantal)*mbtw))
self.view.append(self.mlist[-1])
其中 self.view 是 QTextEdit 视图