Reputation: 13257
I have found that doing
self.combo.setEditable(True)
self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
will align the text in the combobox to the center. But as soon as i do that , the styling that i have applied to the combobox doesn't work and the text that shows inside it will the default plain text . Also i don't want to make it editable and i dont like the GUI effect that occurs when we set it to editable.
Is there an easy way to center align the text and yet retain the same GUI effects as before (like style and behaviour on clicking it) ?
Upvotes: 4
Views: 3043
Reputation: 1844
You can reimplement combobox drawing routine by yourself this way (snippet from project I'm working on):
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 is where text is being drawn.
Upvotes: 3