clicked does not work when mousePressEvent and mouseReleaseEvent are overriden

So I want to add some styles to my button. So I've created a class that derives from QPushButton. I have overriden mousePressEvent and mouseReleaseEvent functions. So far so good. Everything works as expected and buttons change color when pressed and released. The problem comes When in my MainWindow I try to implement on_button_clicked(). It just wouldn't work.

I have experimented a bit with event->accept and event->ignore. that did not work.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

void MainWindow::on_characters_clicked()
{
    qDebug("Hello");
}

void Button::mousePressEvent(QMouseEvent* event)
{
    setStyleSheet(defaultStyle + "Background-color: gray;");
}

void Button::mouseReleaseEvent(QMouseEvent* event) {
    setStyleSheet(defaultStyle + "Background-color: darkgray; border: 1px solid gray; color: white;");
}

I want my button to have both styles on press and release and functionality. I can write an observer class and solve this, but I feel like there has to be an easier solution.

Upvotes: 1

Views: 1061

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

When you override a method you are modifying the behavior of the class, in this case the clicked signal is issued in mouseReleaseEvent, but mouseReleaseEvent is only invoked if mousePressEvent accepts the event, but when modifying code you have eliminated it. The solution is to call the implementation of the parent.

void Button::mousePressEvent(QMouseEvent* event)
{
    setStyleSheet(defaultStyle + "Background-color: gray;");
    QPushButton::mousePressEvent(event);
}

void Button::mouseReleaseEvent(QMouseEvent* event) {
    setStyleSheet(defaultStyle + "Background-color: darkgray; border: 1px solid gray; color: white;");
    QPushButton::mouseReleaseEvent(event);
}

On the other hand I do not see any need to override the mousePressEvent methods since the Qt Style Sheet supports the pseudo-states:

setStyleSheet(R"(
    Button{
      // default styles
      background-color: darkgray; 
      border: 1px solid gray; 
      color: white;
    }
    Button::presed{
      // default styles
      background-color: gray;
    }
)");

Upvotes: 1

Related Questions