Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect that the close button of QWidget is pressed?

Tags:

c++

qt

I create a new QWidget object and I want to know when the close button is pressed.

I have tried the following code:

pWindow = new QWidget();
connect(pWindow , SIGNAL(triggered()), this, SLOT(processCloseButtonWindowsClicked()));

but it give an error:

no signal triggered of pWindow

How to achieve this?

like image 932
Nguyen Huu Tuyen Avatar asked Nov 06 '18 00:11

Nguyen Huu Tuyen


1 Answers

Cause

QWidget does not have a triggered signal.

Solution

I would suggest you to:

  1. Subclass QWidget and reimplement QWidget::closeEvent

  2. Check QEvent::spontaneous to differentiate between a click of the close button and the call to QWidget::close

  3. According to your app's logic either call QWidget::closeEvent(event); to close the widget, or QEvent::ignore to leave it open

Example

I have prepared an example for you of how to implement the proposed solution:

#include <QMainWindow>
#include <QCloseEvent>
#include <QPushButton>

class FooWidget : public QWidget
{
    Q_OBJECT
public:
    explicit FooWidget(QWidget *parent = nullptr) :
        QWidget(parent) {
        auto *button = new QPushButton(tr("Close"), this);
        connect(button, &QPushButton::clicked, this, &FooWidget::close);
        resize(300, 200);
        setWindowTitle("Foo");
    }

protected:
    void closeEvent(QCloseEvent *event) override {

        if (event->spontaneous()) {
            qDebug("The close button was clicked");
            // do event->ignore();
            // or QWidget::closeEvent(event);
        } else {
            QWidget::closeEvent(event);
        }
    }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT
    FooWidget *pWindow;
public:
    explicit MainWindow(QWidget *parent = nullptr) :
        QMainWindow(parent),
        pWindow(new FooWidget()) {
        pWindow->show();
    }
};
like image 200
scopchanov Avatar answered Nov 15 '22 07:11

scopchanov