Search code examples
pythonpython-3.xpyqt

How to center the text in the list of the QComboBox?


a similar question is already answered here: How to center text in QComboBox?

but still I cant find a method how to center the items shown in the list?

enter image description here

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_())

Solution

  • One possible option is to use a delegate:

    from PyQt4 import QtGui, QtCore
    
    class AlignDelegate(QtGui.QStyledItemDelegate):
        def initStyleOption(self, option, index):
            super(AlignDelegate, self).initStyleOption(option, index)
            option.displayAlignment = QtCore.Qt.AlignCenter
    
    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)
            layout = QtGui.QVBoxLayout(self)
            self.combo = QtGui.QComboBox()
            delegate = AlignDelegate(self.combo)
            self.combo.setItemDelegate(delegate)
            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_())