简体   繁体   中英

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?

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM