Вопрос

I'm using a custom ComboBox class because I want to standardize a font for all my combo boxes. I've tried doing this in 3 different ways, as seen in my pyqt class definition below:

class StandardComboBox(QComboBox):
    def _init_(self, parent = None):
        super(StandardComboBox, self).__init__(parent)
        self.setFont(QFont('Courier New', 30))                    #<<< 1
        self.setStyleSheet("font: 30pt \"Courier New\";")         #<<< 2

    def paintEvent(self, e):
        painter = QStylePainter( self )
        painter.setPen( self.palette().color( QPalette.Text ) )

        opt = QStyleOptionComboBox()
        opt.fontMetrics = QFontMetrics(QFont('Courier New', 30))  #<<<3
        self.initStyleOption( opt )
        painter.drawComplexControl( QStyle.CC_ComboBox, opt )

        painter.drawControl( QStyle.CE_ComboBoxLabel, opt)

To call the class all I'm doing is:

self.myComboBox = StandardComboBox()

However, my combo boxes still have the default style and not the font I'm setting. What am I missing? Calling either of the #1 or #2 methods again on a combo box sets the font correctly, but that defeats the purpose of my custom class.

Это было полезно?

Решение

Remove everything, just leave self.setFont(QFont(...)) as it is, inside __init__. This worked for me. The problem with your code is that, you used single leading and trailing underscores for init method. Put double underscores, def __init__(self, parent=None)).

class StandardComboBox(QComboBox):
    def __init__(self, parent = None):
        super(StandardComboBox, self).__init__(parent)
        self.setFont(QFont('Courier New', 30))

This code is enough to change the font of comboBox.

Другие советы

OR this works also:

.setStyleSheet( "QComboBox{ font: 14px 'monospace'; background-color: #fff; color: #000; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top