Button Clicked
1from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel
2
3class MainWindow(QMainWindow, object):
4 def __init__(self, parent=None):
5 super(MainWindow, self).__init__(parent)
6
7 self.init_ui()
8
9 def init_ui(self):
10 self.button = QPushButton("Click Me!", self)
11 self.label = QLabel("Button not clicked.", self)
12
13 self.button.move(50, 20)
14 self.button.clicked.connect(self.on_button_click)
15
16 self.label.move(50, 60)
17
18 def on_button_click(self):
19 self.label.setText("Button clicked!")
20
21if __name__ == "__main__":
22 app = QApplication([])
23 mainWindow = MainWindow()
24 mainWindow.show()
25 app.exec_()
This example connects a click event to the button to change the label’s text.
The
clicked.connect()method is used to connect the method to be executed on button click (theon_button_clickfunction).