How to Display a Message on the Status Bar of a Main Window in a Qt Widget Application in C++


C++


In this article, we show how to display a message on the status bar of a main window in a Qt widget application in C++.

A status bar, as the name suggests, gives you some type of status update. This could be anything such as you pressing, Ctrl + S to save a document, and a message on the status bar states, 'The file has been saved'. Or it could update the certain features of the software application, including the line and column you are currently on or the view zoom percentage.

In the simple application we will create now, we will display a message on the status bar, 'The file has been saved'.

This is shown below.

Message on status bar of a Qt widget in C++

Once we click the Save menu item, the message, 'The file has been saved' appears on the status bar of the window.

So how do we do this in code?

So the first thing is you have to create a program of the QMainWindow class.

You then have to create a Save menu item or any menu item that you want to show a status bar message after it being selected. In this example, we simply do for the Save menu item.

So now for this menu item, click 'Go to Slot' and select the QAction of 'triggered()'

This will create a function that will run when the menu item is selected.

The following code should be placed into the "mainwindow.cpp" file.



So the code is straightforward.

When the save menu is selected, then the method, void MainWindow::on_actionSave_triggered(), runs.

To show a message on the status bar, we reference the status bar using, statusBar(), and use the showMessage() function to show a message on it.

The showMessage() function takes in 1 or 2 paramters.

If you want the message to be shown on the status bar and not erased, in other words, stay on the status bar indefinitely, you only need 1 parameter, the message you want displayed. If you want the message shown for only a period of time and then to disappear, then you specify the time as a second parameter in milliseconds.

So if you just want the message to appear for a certain period of time, you specify the time in milliseconds as the second parameter.

After the Save menu item is selected, the message, 'The file has been saved' will appear for 3 seconds and then disappear.

Again, if you don't specify a second parameter, the message on the status bar will remain there.

And this is how to display a message on the status bar of a window in a Qt widget in C++.


Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...