这里已经回答了类似的问题:How to center text in QComboBox?
但我仍然找不到如何将列表中显示的项目居中的方法?
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_())
一种可能的选择是使用委托:
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_())
我最近尝试过,这对我有用
combo_box = QtWidgets.QComboBox()
combo_box.setEditable(True)
combo_box.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
combo_box.lineEdit().setReadOnly(True)