【问题标题】:Aligning text using format in a QTextEdit in Python在 Python 的 QTextEdit 中使用格式对齐文本
【发布时间】:2020-05-24 22:10:31
【问题描述】:

我想在 QTextEdit 中显示文本。我使用 format() 函数来对齐文本并使它看起来像一个干净的表格。虽然我在 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 得到我想要的东西?或者我应该使用另一个显示小部件(不需要编辑,标签可以,但我喜欢文本编辑的外观)?

【问题讨论】:

  • 您在QTextEdit 实例中使用什么字体?
  • 好问题。我没有指定任何特定的字体,所以我猜是默认字体。我尝试设置“等宽”字体,现在间距很好!我在 Windows 上,但肯定必须在 Mac 上使用我的程序,所以我试图使用 systemFont 函数来检索默认的固定宽度字体,但似乎无法使其工作。我正在使用 PySide 1.2.4 版

标签: python qt format qtextedit


【解决方案1】:

我使用的是没有固定宽度的默认字体,因此没有对齐。将字体设置为像“等宽”这样的固定宽度字体解决了我的问题:

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

我使用“setStyleHint”来指示如果在系统上找不到“monospace”,Qt 应该使用哪种字体,“QFont.TypeWriter”指示选择固定间距的字体,以便仍然遵守对齐方式。

【讨论】:

  • 感谢您发布解决方案 :)
【解决方案2】:

通过使用 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 视图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2020-03-16
    • 2022-01-10
    相关资源
    最近更新 更多