2014-12-08 59 views
1

格式文本我有這樣的代碼片段:PySide:在QComboBox

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中使用比例字體的文本?謝謝。

回答

1

您的算法很好,但它只能與您使用的比例字體中標準空間的寬度一樣精確。

要獲得更精確的結果,請使用盡可能最薄的whitespace character。對於支持unicode的字體,這將是HAIR SPACE U+200A

在Linux(使用幻覺記憶Sans字體),我可以準確地在您的示例腳本以下兩行改變重現(3)

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

工作正常的Linux,Windows 7和Windows 8。在Windows XP中不起作用,因爲UTF8未啓用,但此解決方案對我來說已足夠。謝謝!。 – mangelo 2014-12-10 15:43:26