How to create a correct exit button in qt

2019-04-21 09:14发布

问题:

I'm trying to create an exit button that correctly closes the GUI I have made in QT. I have tried doing this in the following way:

#include <QtGui/QApplication>
#include "mainwindow.h"

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

int window_width = QApplication::desktop()->width();
int window_height = QApplication::desktop()->height();

MainWindow w;

QPushButton * quit_btn = new QPushButton;
quit_btn->setParent(w.centralWidget());
quit_btn->setGeometry(window_width-50,12,32,32);

QObject::connect(quit_btn,SIGNAL(clicked()),qApp,SLOT(quit()));

w.resize(window_width,window_height);
w.show();

return a.exec();
}

Unfortunately when I push the button, the debugger gives an error:

Invalid address specified to RtlFreeHeap( 003E0000, 0028F950 )

Can anybody point me in the right direction?

回答1:

Connect the button's clicked() signal to your main window's close() slot. That way things are cleaned up properly.