如何将 QComboBox 中的文本设置为居中对齐而不使其在 PyQt 中可编辑
How to set the text in the QComboBox to align to the center without making it editable in PyQt
我发现
self.combo.setEditable(True)
self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
会将组合框中的文本居中对齐。但是一旦我这样做,我应用到组合框的样式就不起作用,其中显示的文本将默认为纯文本。我也不想让它可编辑,我不喜欢当我们将它设置为可编辑时出现的 GUI 效果。
是否有一种简单的方法可以使文本居中对齐并保留与以前相同的 GUI 效果(例如单击它时的样式和行为)?
您可以通过这种方式自己重新实现组合框绘图例程(我正在处理的项目的片段):
class CustomComboBox(QtGui.QComboBox):
...
def paintEvent(self, evt):
painter = QtGui.QStylePainter(self)
painter.setPen(self.palette().color(QtGui.QPalette.Text))
option = QtGui.QStyleOptionComboBox()
self.initStyleOption(option)
painter.drawComplexControl(QtGui.QStyle.CC_ComboBox, option)
textRect = QtGui.qApp.style().subControlRect(QtGui.QStyle.CC_ComboBox, option, QtGui.QStyle.SC_ComboBoxEditField, self)
painter.drawItemText(
textRect.adjusted(*((2, 2, -1, 0) if self.isShown else (1, 0, -1, 0))),
QtGui.qApp.style().visualAlignment(self.layoutDirection(), QtCore.Qt.AlignLeft),
self.palette(), self.isEnabled(),
self.fontMetrics().elidedText(self.currentText(), QtCore.Qt.ElideRight, textRect.width())
)
...
painter.drawItemText
call 是绘制文本的地方。
我发现
self.combo.setEditable(True)
self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
会将组合框中的文本居中对齐。但是一旦我这样做,我应用到组合框的样式就不起作用,其中显示的文本将默认为纯文本。我也不想让它可编辑,我不喜欢当我们将它设置为可编辑时出现的 GUI 效果。
是否有一种简单的方法可以使文本居中对齐并保留与以前相同的 GUI 效果(例如单击它时的样式和行为)?
您可以通过这种方式自己重新实现组合框绘图例程(我正在处理的项目的片段):
class CustomComboBox(QtGui.QComboBox):
...
def paintEvent(self, evt):
painter = QtGui.QStylePainter(self)
painter.setPen(self.palette().color(QtGui.QPalette.Text))
option = QtGui.QStyleOptionComboBox()
self.initStyleOption(option)
painter.drawComplexControl(QtGui.QStyle.CC_ComboBox, option)
textRect = QtGui.qApp.style().subControlRect(QtGui.QStyle.CC_ComboBox, option, QtGui.QStyle.SC_ComboBoxEditField, self)
painter.drawItemText(
textRect.adjusted(*((2, 2, -1, 0) if self.isShown else (1, 0, -1, 0))),
QtGui.qApp.style().visualAlignment(self.layoutDirection(), QtCore.Qt.AlignLeft),
self.palette(), self.isEnabled(),
self.fontMetrics().elidedText(self.currentText(), QtCore.Qt.ElideRight, textRect.width())
)
...
painter.drawItemText
call 是绘制文本的地方。