1

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_())
TomK
  • 244
  • 2
  • 12

1 Answers1

2

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • but what if the combobox should not be editable ... because if I set it afterwars to setEditable(False) then it is again on the left side .. – TomK Jan 19 '19 at 16:44
  • With PyQt5 you can use self.combo.lineEdit().setReadOnly(True) which should make is to the text is not editable (did not test with PqQt4). – wutangforever Mar 10 '23 at 17:29