0
votes

So, I have a custom QLabel class that I'm using as a button. When the label is clicked, the background color changes from red to green. On the mouse release event, the background goes back to red. However, if I add a slot to the widget's "clicked" signal, the mouse release event appears to never be fired. The label stays green. At the moment, I have it so when the label is clicked, a QMessageBox is displayed. Yet, even after the messagebox is closed, the label stays green. I tried connecting it's focusOutEvent to the same slot that turned the background red, yet it's still not working. How can I get the button to revert to a red background immediately after the mouse is released? I hope this makes sense. Any ideas?

#include "ubtn.h"
QString sty  =  "ubtn{background:red;}";
QString styd =  "ubtn{background:green;}";

QWidget *obj;
ubtn::ubtn(QWidget *parent) :
    QLabel(parent)
{
    this->setStyleSheet(sty);
    connect(this, SIGNAL(onBlur(bool)), SLOT(defaultBtn()));
}

void ubtn::defaultBtn()
{
    this->setStyleSheet(sty);
    this->repaint();
}

void ubtn::downBtn()
{
    this->setStyleSheet(styd);
    this->repaint();
}

void ubtn::mousePressEvent(QMouseEvent *ev)
{
    downBtn();
    emit clicked();
}

void ubtn::mouseReleaseEvent(QMouseEvent *ev)
 {
    defaultBtn();
 }

void ubtn::focusOutEvent(QFocusEvent *e)
 {
    QLabel::focusOutEvent(e);
    emit(onBlur(true));
 }
2

2 Answers

0
votes

Try this in the defaultBtn function:

setStyleSheet(sty);
style()->unpolish(this);
style()->polish(this);
0
votes

Okay, so the problem is that when you show the QMessageBox, the QMessageBox becomes the active window... so when the user releases the mouse button the mouseReleaseEvent goes to the QMessageBox rather than to your ubtn.

I think the easiest way around the problem would be to for ubtn to call "emit clicked()" from the mouseReleaseEvent() method rather than mousePressEvent(); that way the button can revert to its regular color before the QMessageBox is shown, and therefore active-window-change takes place.