Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to implement an exit button in my application, which has the following setup: I have a main function which looks like this:

QApplication a(argc, argv);
MainWindow w;

w.show();

return a.exec();

I also have a mainWindow function which has been generated by the QT Creator IDE.
I design the GUI with the Qt Designer and when I want a pushbutton to do something when clicked, I use a function like this:

void on_selection_clicked();

I hope the setup is now sufficiently described.
Now to my problem: I want to implement a button, which, when clicked, terminates the window and the application. I first tried implementing this in a function like this:

void on_exit_clicked();

But I don't know that to to here.
Then I heard of a aproach via QObject::connect, but I have two questions:
1.) Where should I put this? In the main function?
2.) can I access the object simply via the object name given in the QT Designer?

share|improve this question

2 Answers 2

up vote 1 down vote accepted
  1. no you should connect it in the constructor of the MainWindow

    connect(ui->exit,SIGNAL(clicked()),QCoreApplication::instance(), SLOT(exit()));
    

    QCoreApplication::instance()->exit() will quit the application

  2. yes through the ui field in MainWindow see the code above

share|improve this answer
    
That works, but I'm using a MainWindow, so the SLOT mustn'be exit() (which MainWindow doesn't know), but close(). –  BlackMamba Sep 18 '13 at 20:06

I don't know which Qt version you use, so I will suppose Qt 5.0 (signal/slot mechanims was updated).

  • QWidget has slot QWidget::close().

  • QPushButton provides signal QPushButton::clicked(bool checked = false)

So you can connect them in constructor of your MainWindow:

QObject::connect(your_button, &QPushButton::clicked, this, &QWidget::close());

Also I suggest to look into the files generated from *.ui files - so you have deeper understanding of what's going on.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.