0

I made a window and a button in it. I want the button to close the window when clicked, BUT I want to do it by a public slot that I created and which contains the close slot of the QWidget, instead of doing it using the default QWidget::close(). Here is my code.

window.h

#ifndef FENETRE_H
#define FENETRE_H

#include <QObject>
#include <QWidget>
#include <QPushButton>

class fenetre: public QWidget
{
Q_OBJECT
public:
    fenetre();

public slots:
    void another();

private:
    QPushButton *button1;
};

#endif // FENETRE_H

window.cpp

#include "fenetre.h"

fenetre::fenetre():QWidget()
{
    setFixedSize(300,300);
    button1=new QPushButton("click",this);

    connect(button1,SIGNAL(clicked()),this,SLOT(another()));
}

void fenetre::another()
{
    fenetre().close();
}

main.cpp

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include "fenetre.h"

int main(int argc , char *argv[])
{
    QApplication app(argc,argv);

    fenetre fen;
    fen.show();

    return app.exec();
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93
Barbell
  • 194
  • 1
  • 6
  • 19

1 Answers1

0

The problem is the code in the slot: fenetre().close();. Here fenetre() creates a new object on which close() is called. So simply call close() in the slot and all should work as you expect.

Also consider to use the Qt5 style connect with function pointers since they are more secure in general and dont require you to tag functions with "slots" in the header file:

connect(button1, &QPushButton::clicked, this, &fenetre::another);
Lorenz
  • 503
  • 2
  • 9