Python 如何将QComboBox列表中的文本居中?
这里已经回答了一个类似的问题: 但是我仍然找不到一种方法如何将列表中显示的项目居中Python 如何将QComboBox列表中的文本居中?,python,python-3.x,pyqt,Python,Python 3.x,Pyqt,这里已经回答了一个类似的问题: 但是我仍然找不到一种方法如何将列表中显示的项目居中 一种可能的选择是使用委托: from PyQt4 import QtGui, QtCore class AlignDelegate(QtGui.QStyledItemDelegate): def initStyleOption(self, option, index): super(AlignDelegate, self).initStyleOption(option, index)
一种可能的选择是使用委托:
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_())
但是如果组合框不可编辑怎么办。。。因为如果我在afterwars中将其设置为setEditable(False),那么它再次位于左侧。。
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_())