Search code examples
pythonpyqtpyqt5qtstylesheetsqpushbutton

Pyqt5 changing qpushbutton stylesheet when hovering over it


So I'm making an application using pyqt5 and what I'm trying to do is make a qpushbutton of a custom style sheet that changes color when your mouse hovers over it. I searched it up and found that in python the following code works to change the hovering settings:

button.setStyleSheet("QPushButton::hover"
                     "{"
                     "background-color : lightgreen;"
                     "}")

and when I tested it out, it worked, but then it removed my custom stylesheet.

button.setStyleSheet("background-color: #2B5DD1; color: #FFFFFF ; border-style: outset; 
padding: 2px ; font: bold 20px ; border-width: 6px ; border-radius: 10px ; border-color: #2752B8;")
                                    

was my original code with just my style sheet which worked and then when I tried combining the two as follows:

to_meetings.setStyleSheet("background-color: #2B5DD1; color: #FFFFFF ; border-style: outset; padding: 2px ; font: bold 20px ; border-width: 6px ; border-radius: 10px ; border-color: #2752B8;"
                          "QPushButton::hover"
                          "{"
                          "background-color: #112452;"
                          "}")  

It ran just fine, but didn't show the hover settings and instead just showed my custom stylesheet. Any idea on how to incorporate a custom stylesheet as well as hover settings?


Solution

  • Just as you defined the QPushButton style with the hover pseudo-state, you can define it for the regular state.

    QPushButton {
        background-color: #2B5DD1;
        color: #FFFFFF;
        border-style: outset;
        padding: 2px;
        font: bold 20px;
        border-width: 6px;
        border-radius: 10px;
        border-color: #2752B8;
    }
    QPushButton:hover {
        background-color: lightgreen;
    }
    

    See customizing QPushButton examples in Qt docs