【问题标题】:PySide: Formatted text in QComboBoxPySide:QComboBox 中的格式化文本
【发布时间】:2014-12-08 05:57:25
【问题描述】:

我有这段代码:

import PySide.QtGui

app = PySide.QtGui.QApplication('')
wnd = PySide.QtGui.QWidget()
mly = PySide.QtGui.QVBoxLayout()
combo = PySide.QtGui.QComboBox()

table = [ ('Lorem','ipsum','dolor','sit','amet'),
          ('Aliquam','sodales','nunc','eget','lorem'),
          ('Vivamus','et','sapien','mattis','vulputate'),
          ('Integer','ac','dolor','commodo','cursus'),
          ('Sed','sed','erat','non','magna'),
          ('Duis','vestibulum','eu','tortor','euismod') ]

combo.clear()
for (one,two,three,four,five) in table:
    combo.addItem('%-12s | %-12s | %-12s | %-12s | %-12s' % (one,two,three,four,five))

mly.addWidget(combo)
mly.addStretch(1)
wnd.setLayout(mly)
wnd.show()
app.exec_()

我已经获得了this (1),并且我正在寻找类似 (2) 的内容:所有列都以表格形式列出。

组合框具有标准的比例字体(来自 QtDesigner 的 MS Shell Dlg 2)。我不想使用等宽字体。

我尝试用combo.fontMetrics().boundingRect(text).width() 计算每列的最大像素宽度,并用空格填充每一列:

borde = '  '
unspc = ' '
maxwdt = {0:0, 1:0, 2:0, 3:0, 4:0}
for lstlin in table:
    for (ndx,val) in enumerate(lstlin):
        unwdt = combo.fontMetrics().boundingRect(borde + val + borde).width()
        if (unwdt > maxwdt[ndx]):
            maxwdt[ndx] = unwdt

combo.clear()
for lstlin in table:
    txtlin = ''
    for (ndx,val) in enumerate(lstlin):
        txtcmp = borde + val + borde
        while (combo.fontMetrics().boundingRect(txtcmp).width() < maxwdt[ndx]):
            txtcmp += unspc
        txtlin += txtcmp + '|'
    combo.addItem(txtlin)

我已经获得了(3)

还有其他方法可以用比例字体格式化文本以在 QComboBox 中使用吗?谢谢。

【问题讨论】:

    标签: pyside qcombobox


    【解决方案1】:

    您的算法很好,但它只能与您使用的比例字体中标准空间的宽度一样准确。

    要获得更准确的结果,请使用最薄的whitespace character。对于具有良好 unicode 支持的字体,这将是 HAIR SPACE U+200A

    在 Linux 上(使用 DejaVu Sans 字体)我可以通过更改示例脚本中的以下两行来准确重现 (3)

    # hair-space
    unspc = '\u200a'
    borde = unspc * 10
    

    【讨论】:

    • 在 Linux、Windows 7 和 Windows 8 中运行良好。在 Windows XP 中无法运行,因为未启用 UTF8,但这个解决方案对我来说已经足够了。谢谢!。
    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多