I have this snippet of code:
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_()
I have obtained this (1) and I'm looking for something like (2): all columns tabulated.
The combobox have the standard proportional font (MS Shell Dlg 2 from QtDesigner). I don't want to use monospaced font.
I have tried to calculate the maximum width in pixels of every column with combo.fontMetrics().boundingRect(text).width()
and fill every column with spaces:
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)
and I have obtained (3).
There are any other method to format a text with proportional font for use in a QComboBox?. Thanks.
Your algorithm is fine, but it can only be as accurate as the width of a standard space in the proportional font you are using.
To get more accurate results, use the thinnest possible whitespace character available. For fonts with good unicode support, this will be the HAIR SPACE U+200A
.
On Linux (using the DejaVu Sans font) I can exactly reproduce (3) by changing the following two lines in your example script:
# hair-space
unspc = '\u200a'
borde = unspc * 10