Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
Bartis Áron Avatar asked Dec 01 '25 02:12

Bartis Áron


1 Answers

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.
like image 52
Marek R Avatar answered Dec 03 '25 15:12

Marek R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!