How to center text in QComboBox?

alphanumeric picture alphanumeric · May 20, 2014 · Viewed 10.2k times · Source

I've tried using QComboBox's model() with no apparent success. I wonder if it would be possible to align a text at the center of QCombobox. Aside from text alignment it seems the item's font is not effected by changing its PointSize....

    combo=QtGui.QComboBox()
    comboModel=combo.model()

    for name in ['one','two','three']:
        item = QtGui.QStandardItem(name)
        itemFont = item.font()
        itemFont.setPointSize(8)
        item.setFont(itemFont)
        # item.setAlignment(QtCore.Qt.AlignCenter)
        comboModel.appendRow(item)

Answer

NorthCat picture NorthCat · May 21, 2014

You can use setAlignment method:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.combo = QtGui.QComboBox()
        self.combo.setEditable(True)
        self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
        self.combo.addItems('One Two Three Four Five'.split())
        layout.addWidget(self.combo)


if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())