c++qteventsqt5

Why WindowStateChange event does not work with me


I want when change the window state from state to another, for example: WindowMaximized, WindowMinimized, WindowFullScreen, when change the window state performs something.

The function used

void Widget::WindowStateChange(QEvent *event){
    if (event->WindowStateChange == Qt::WindowMaximized) {
        QMessageBox::information(this, "", "Something happen.");
    }
}

There is nothing happening when implement the previous function.


Solution

  • Your method is never called. There are several virtual methods in QWidget which are called when some events happen: actionEvent, changeEvent, closeEvent and other.

    You can reimplement them and process these events.

    To catch window state changes method changeEvent is used.

    It is called when not only window state is changed, but also font, style etc. That is why you need to filter an event you want to process. You can do it by checking event->type().

    void Widget::changeEvent(QEvent* e)
    {
       if (e->type() == QEvent::WindowStateChange)
       {
          QWindowStateChangeEvent* ev = static_cast<QWindowStateChangeEvent*>(e);
          if (!(ev->oldState() & Qt::WindowMaximized) && windowState() & Qt::WindowMaximized)
          {
              QMessageBox::information(this, "", "Window has been maximized");
          }
       }
       QWidget::changeEvent(e);
    }