PyQt5 - How to add action to a button?

PyQt5 - How to add action to a button?

To add an action to a button in PyQt5, you typically connect the button's clicked signal to a slot (a function or method that gets called in response to the signal). Here's a step-by-step guide on how to do this:

1. Install PyQt5:

If you haven't already, install PyQt5 using pip:

pip install pyqt5 

2. Create a Basic App with a Button:

Here's an example of creating a simple PyQt5 application with a button. When the button is clicked, a message will be printed to the console.

import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 Button Click Example' self.initUI() def initUI(self): self.setWindowTitle(self.title) # Create a button button = QPushButton('Click Me', self) # Connect the button's clicked signal to a slot (our button_click method) button.clicked.connect(self.button_click) # Position the button button.move(50, 50) # Set the window size self.setGeometry(100, 100, 200, 200) self.show() # Define the slot (action to be taken when the button is clicked) def button_click(self): print('Button was clicked!') if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) 

In the above code:

  • A QPushButton object is created with the text "Click Me".
  • The button's clicked signal is connected to the button_click method using the connect method. This means that when the button is clicked, the button_click method will be called.
  • The button_click method simply prints a message to the console.

You can replace the action inside the button_click method with any other action you'd like to perform when the button is clicked.


More Tags

rows printing rhel cmd auto-increment xcode4 cursor-position oracle9i nested find

More Programming Guides

Other Guides

More Programming Examples