Reputation: 45
I created class that inherit from QAbstractButton and stylesheets does not work in this class. How can I use stylesheet in class that inherit from QAbstractButton?
MyButton::MyButton(QWidget *parent):
QAbstractButton(parent)
{
setGeometry(0, 0, 100, 50);
setText(tr("My button"));
setStyleSheet("QAbstractButton:hover{background-color:blue}");
}
void MyButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(rect(), QColor("black"));
painter.fillRect(rect().x() + 2, rect().y() + 2,
rect().width() - 4, rect().height() - 4,
QColor("red"));
painter.drawText(rect(), Qt::AlignCenter, text());
}
Upvotes: 0
Views: 503
Reputation: 2886
Hi and Welcome here on SO!
Once you override the paintEvent method you are taking full responsibility on how the widget will be painted. Thus, the stylesheet will not work since the QStyle used by your application will not be involved.
If you just need a button that changes color whenever the mouse is over it, you don't need to derive the QAbstractButton class at all. Just use a standard QPushButton and style it accordingly.
Otherwise, if you want to be in full control and paint all by yourself, you can implement the hover effect easily by using the enterEvent() and leaveEvent() functions. Just add a boolean in your class (i.e. "isHover") and write something like this:
MyButton::MyButton(QWidget *parent):
QAbstractButton(parent)
{
isHover = false;
setGeometry(0, 0, 100, 50);
setText(tr("My button"));
}
void MyButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(rect(), (isHover ? Qt::blue : Qt::red));
painter.fillRect(rect().x() + 2, rect().y() + 2,
rect().width() - 4, rect().height() - 4,
QColor("red"));
painter.drawText(rect(), Qt::AlignCenter, text());
}
void MyButton::enterEvent(QEvent *event)
{
isHover = true;
}
void MyButton::leaveEvent(QEvent *event)
{
isHover = false;
}
Upvotes: 1