Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the text in the QComboBox to align to the center without making it editable in PyQt

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) ?

like image 404
Natesh bhat Avatar asked Oct 27 '25 05:10

Natesh bhat


1 Answers

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.

like image 110
bakatrouble Avatar answered Oct 29 '25 18:10

bakatrouble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!