Bartis Áron
Bartis Áron

Reputation: 668

Qt widget detects mouse events when cursor is not over the widget

I created a very little Qt project with two classes. One of them is a reimplemented widget with these methods:

#include "mywidget.h"

// Qt
#include <QMouseEvent>
#include <QMessageBox>

// Debug
#include <QDebug>

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
}

void MyWidget::mousePressEvent(QMouseEvent *event)
{
    QMessageBox::information(this, "", "");
}

The other is the main class with these method:

#include "mainwindow.h"

// My headers
#include "mywidget.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    this->setCentralWidget(new QWidget());

    QWidget *mw = new MyWidget(this->centralWidget());


    // setting backgrounds for visibility
    mw->setPalette( QPalette(Qt::green) );
    mw->setAutoFillBackground(true);

    mw->move(20, 20);
    mw->resize(50, 50);
}

MainWindow::~MainWindow()
{
}

Very simple. In the main window only one widget can be found. This widget creates a message box, when pressed the mouse button. After the message box appeared, if I click with the left mouse button on the OK button, then everything works fine, but if I press "Space bar" or "Enter", to activate the button, the program goes wild: If I click anywhere (either on the area of the widget or not), the green widget acts like I clicked on it and the message box pops up.

Why is it? What can I do to suppress this behaviour?

Upvotes: 3

Views: 4908

Answers (1)

Marek R
Marek R

Reputation: 38112

With current implementation of mousePressEvent you are accepting mouse event and your widget becomes a mouse grabber. But then, suddenly you are crating new window which steals the focus and your widget doesn't receive the mouse release event so it doesn't release the mouse grab.

When you click the message box it takes over the mouse grab and everything works as it's supposed to. In other cases your widget regains focus and your widget still have a grab on mouse.

I would say it is Qt bug (on window focus change the widget should release the mouse) which will appear only if combined with your buggy code.

There are two solutions:

  1. Do not accept mouse press events, add event->ignore(); in mousePressEvent
  2. Move creation of message box to mouseReleaseEvent. An empty implementation of mousePressEvent is required, too.

Upvotes: 1

Related Questions