How to detect mouse click outside the application in Qt [closed]

-4

I am developing an application in Qt, I need to detect when you click outside the application to alternate hide () - show () with each click

Solved: through the event void changeEvent (QEvent * e); where we can capture the loss of focus of the current window, we know when we click outside of our application.

MainWindow.h

    void changeEvent(QEvent * e);

MainWindow.cpp

     void MainWindow::changeEvent(QEvent * e){
    if(e->type() == QEvent::ActivationChange && this->isActiveWindow()){
       qDebug("focus in");
    } else {
       qDebug("focus out");
    }

}

    
asked by Miguel Reche 12.09.2017 в 11:05
source

1 answer

1

You can control the position of the mouse to know when you lose the focus of the window and thus control when you click outside:

if (event->type() == QEvent::FocusOut)
{
        qDebug("focus lost");
        QPoint p=QCursor::pos();
        qDebug() << "mouse position=" << p;
        if ((p.x() >= 100 && p.x() <= 300) && (p.y() >= 100 && p.x() <= 700))
       {
    qDebug("hiding window");
    hide();
       }
}
_____________________________

EDIT: You must create a method that listens to mouse events or manages a QEventFilter, the events to be handled would be something like this:

if (event->type() == QEvent::FocusOut)
{
        qDebug("focus lost");
        return true;
}
else if(event->type() == QEvent::MouseButtonPress)
{
    QPoint pos = dynamic_cast<QMouseEvent*>(event)->pos();
        qDebug() << "global=" << dynamic_cast<QMouseEvent*>(event)->globalPos();
        return false;
}
    
answered by 12.09.2017 / 11:29
source