How to Add a Exit Menu Item to a Qt Widget Application in C++


In this article, we show how to add an exit or quit menu item to a Qt widget application in C++.

So when we are dealing with menus in the Qt software, we are dealing with main windows.

The QMainWindow class creates a program that features a main window. In this main window, you can put things that are typical of programs. For example, when you click on NotePad or Wordpad or Microsoft Word, what comes up after you click is a window. It's a window that features a menu such as File, Edit, View, Help, etc. as well as a text area to be able to type in things.

So when we're working with a QMainWindow class, we're working with a main window similar to what you find in programs such as NotePad, WordPad, Microsoft Word, etc.

Notice that in programs such as NotePad and WordPad, under the File menu tab, there is normally an Exit menu item, which allows you to close the program.

This is shown below in a Qt widget application.

Exit menu item in a Qt widget in C++

This Exit menu item is common in many desktop software applications.

So how can we place this exit menu item in a window in a Qt widget application with the functionality to close the program out?

Once you create the QMainWindow class application and create an Exit or Quit menu item, then you need to add the following code to the mainwindow.cpp file.

So the function, void MainWindow::on_actionExit_triggered(), is the function that is triggered when the Exit menu item is clicked.

Within this function, the line, QApplication::quit();, closes out the program's window, thus terminating the program.

And this is how we can add an Exit or quit menu item to a Qt widget application in C++.

Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...