如何在QComboBox列表中居中显示文本?

时间:2019-01-18 23:54:37

标签: python python-3.x pyqt

这里已经回答了类似的问题:How to center text in QComboBox?

但是我仍然找不到一种方法来使列表中显示的项居中?

enter image description here

2^Θ(m)

1 个答案:

答案 0 :(得分:1)

一个可能的选择是使用委托:

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