How to Create a Message Box in a Qt Widget Application in C++


In this article, we show how to create a message box in a Qt widget application in C++.

A message box is the typical pop-up window that displays a message after a certain action, such as when a user clicks on a button.

In the example below, we are going to create a simple Qt widget which has a single button. When this button is clicked, a message box is shown that displays a message and has an OK button.

The message that will be displayed is, "You clicked the button", and then there is an Ok button.

Let's go over the code below.

You can do this in code by adding the following in the "widget.ui" file.

This adds a button to the GUI.

Now that the button is added, we next need to add functionality to the button, so that a message box is displayed when the button is clicked.

We add this functionality in the "widget.cpp" file.

The full code in the "widget.cpp" file is shown below.

This now adds functionality so that the button click causes a message box to appear.

So to add functionality to the button click, we add the line, void Widget::on_pushButton_clicked() { }. The action you want done goes in between the curly braces. Since the button has a name attribute, pushButton, this is why it appears in this line. Whatever the name attribute of the item you want clicked is goes after on_

When the button is clicked, we want to create a message box that displays a message. In this case, "You clicked the button"

We also had an Ok button to the message box.

this refers to the element with the name attribute of pushButton.

"Message" is the title of the message box.

"You clicked the button" is the message in the message box, or the contents of the message box.

QMessageBox::Ok creates an Ok button in the message box.

The message box that appears due to the code above is shown below.

A message box in qt widget application in C++

Let's do one more modification to the above code.

The message box above has one button, an OK button.

Below we add a second button, a cancel button.

To add a cancel button, in addition to the Ok button, we add, QMessageBox::Cancel, to QMessageBox::information

Now the message box has an OK and cancel button.

This is shown below.

A message box with Ok and cancel buttons in qt widget application in C++

And this is how to create a message box in a Qt widget application in C++.

Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...