This PyQt5 Tutorial will show you how to create message boxes/popup windows using pyqt. We will use the QMessageBox class to accomplish this.
Creating a Basic GUI
I've started this tutorial by creating a very minimal GUI that contains one button. This way we can use the button press to trigger a popup/mesagebox.
This is what my GUI looks like:
To make our lives a little easier we will start by importing the QMessageBox class. This way each time we want to reference it we can use it directly.
Creating a MessageBox
Note: I'm placing the code seen below inside the method that is linked to my button press. This way when the button is clicked a messagebox will appear on the screen.
Everytime we create a new popup window we need to create a new instance of QMessageBox.
Then we can start changing some properties of the messagebox like the title and the text.
The method names are pretty intuitive so I'll pass on explaining them.
We will add some more to our messagebox later but for now lets test it out. To actually see the messagebox when we run the code we need to add one last line to the end of our method:
And this is what we get when we click the button!
Adding an Icon
A nice feature that our message boxes have it the ability to add an icon!
List of Icons
Here's what our messagebox looks like with the Critical icon.
Now it's time to change the buttons that show up in our QMessageBox. To do this we need to first select from a list of buttons that we'd like.
List of Buttons
We can add any combinations of these buttons to our message box by using the following:
We can also set the button that will be highlighted by default by using:
Now our messagebox looks like this!
Getting Button Pressed
Now that we've learned how to add more than one button is probably important to determine which button the user is clicking.
To do this we need to create a new method/function that takes one argument. This argument will be the button widget that was clicked.
No we can link our messagebox to trigger that method when any button is pressed.
Now when we click a button on the messagebox it's text will be printed out to the console.
A few other things we can add are listed below:
This is the text that shows below the main text.
This will generate a new button that will allow us to expand the message box and view more details.