How To Use Python PyQt5 To Prompt A Dialog With Button

This article will tell you how to use the python PyQt5 library to implement a prompt dialog, it will tell you how to set the dialog title, tooltip text, size, and position coordinates.  It also adds a button on the center of the dialog, when you click the button, it will print a text in the console. When you mouse hover on the button or the dialog window, it will prompt the tooltip text.

use python pyqt5 to implement a dialog and button

Below is the example source code, you can read the comments to learn more.

# Import python sys module.
import sys
 
# Import the PyQt5 QtWidget library. 
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QAction


# This function will be invoked when the button is clicked.
def btn_on_click():
    # Print the text in the console.
    print("The button is clicked.")

if __name__ == '__main__':
    
    # Create the QApplication object.
    app=QApplication(sys.argv)
 
    # Create a QWidget object to display a dialog window.
    dlg = QWidget()
    
    # Set the QWidget dialog left, top coordinates and width and height value.
    left = 10
    top = 100
    width = 300
    height = 100
    dlg.setGeometry(left, top, width, height)
    
    # When you mouse hover on the dialog, it will display the below string in tool tip.
    dlg.setToolTip("This dilog is created with python Qt5")
    
    # Set the dialog title.
    dlg.setWindowTitle("This dilog is created with python Qt5")
    
    # Create a QPushButton object on the above dialog.
    btn = QPushButton("Click",dlg)
    
    # Calculate the button x coordinate.
    btn_x = (width - btn.width())/2
    # Calculate the button y coordinate.
    btn_y = (height - btn.height())/2
    # Move the button to the center of the dialog.
    btn.move(btn_x, btn_y)
    
    # When you mouse hover on the button, it will display the below tool tip text.
    btn.setToolTip("This is a Qt5 button")
    
    # Add a click event handler function to the button, when the button is clicked, it will call the function btn_on_click.
    btn.clicked.connect(btn_on_click)
 
    # Display the QWidget dialog.
    dlg.show()
 
    # Execute the application.
    app.exec_()

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky