如何让QComboBox列表中的文本居中?

问题描述 投票:0回答:2

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

但我仍然找不到如何将列表中显示的项目居中的方法?

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_())
python python-3.x pyqt
2个回答
2
投票

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

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

0
投票

我最近尝试过,这对我有用

combo_box = QtWidgets.QComboBox()
combo_box.setEditable(True)
combo_box.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
combo_box.lineEdit().setReadOnly(True)
© www.soinside.com 2019 - 2024. All rights reserved.