Question

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?

Was it helpful?

Solution

  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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top