Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How change text color in paintEvent() method in subclass of QPushButton?



  • Hi,

    Like in a topic - How change text color in paintEvent() method in subclass of QPushButton?

    I tried:

    void myButton::paintEvent(QPaintEvent *)
    {
        QStyleOptionButton option;
        option.initFrom(this);
    
        option.palette.setColor(QPalette::Text,QColor(Qt::red));
        option.text = "randomText";
    
        QPainter painter(this);
        style()->drawControl(QStyle::CE_PushButton, &option, &painter, this);
    }
    

    And I can change button's text to "randomText", but I can't change his color ( I tried change his background too ). Of course I can use styleEsheet, but I want to use only QStyleOptionButton.

    EDIT:
    I don't understand that information in QStyleOption doc ( QPalette QStyleOption::palette ):

    This variable holds the palette that should be used when painting the control
    

    I change option.palette like this:

    option.palette.setColor(QPalette::Text,QColor(Qt::red));
    

    so why the control isn't painted using this palette settings like color?

    EDIT2:
    I find solution... It was very easy :D

    option.palette.setColor(QPalette::ButtonText, QColor(Qt::red));
    

Log in to reply