简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM