I try to make a custom QPushButton
with a stylesheet. I want to custom color of button when we mouse over it. It works, but I want to put a transition duration.
But in Qt this option is not available.
Here is my custom button:
#include "bouton.h"
Bouton::Bouton(QString title, QWidget *parent) : QPushButton()
{
setGeometry(50,50,120,40);
setText(title);
setMinimumHeight(30);
setParent(parent);
setStyleSheet(" QPushButton {"
"border-radius: 5px; "
"border: 1.5px solid rgb(91,231,255); "
"background-color: white; }"
"QPushButton:pressed {"
"border: 1.4px solid rgb(73,186,205); }"
"QPushButton:hover {"
"font-size: 16px;"
"transition: 0.9s; }");
}
The argument "transition 0.9s" doesn't work.
Here is an example in CSS.
Are there other ways to do this?
Cause
QSS is not CSS. There is no transition property. Here is a list of all available properties.
Solution
Instead of using stylesheets, I would suggest you to take another path, which is longer, but gives you more flexibility. Here is the solution:
Create a subclass of
QPushButton
, e.g.AnimatedHoverButton
Get notified about
QEvent::HoverEnter
andQEvent::HoverLeave
events by reimplementingQPushButton::event
Create the
in
andout
transition by usingQVariantAnimation
Paint the button by reimplementing the
QPushButton::paintEvent
event handler and taking into account the current value of the animationNote: This solution uses the widget's palette to set the start and end values of the animation.
Example
The solution might seem complicated, but fortunatelly I have prepared a working example for you of how to implement and use the
AnimatedHoverButton
class.The following code fragment uses the
AnimatedHoverButton
class to produce a result, similar to the CSS example you have provided:The full code of the example is available on GitHub.
Result
The given example produces the following result:
You can use Animation.
MyButton.h
MyButton.cpp
It will conflict with external qss setting. So set all qss in
SetColor
.