Hello Python developer, hope you're good today!
Today, we will learn about PyQt button and event connection.
For button creation in your window, use 'QPushButton' class as following exercise.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(200, 200, 400, 300)
self.setWindowIcon(QIcon("PyQt window sample icon.png"))
btn = QPushButton("Button 1", self)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
Python source code in Github link : https://github.com/Cevastian/Python-Developer-start-today/blob/master/PyQt_Button_exercise%20001.py
Code run result :
Can you click the "Button 1"? Yes, you can click it but threr is no action by button click.
Now, we will connect the 'Event' when we click this 'Button 1'.
Let's type and run following Python codes.
# PyQt Window Button - Event connection exercise
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class QtWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(200, 200, 400, 300)
self.setWindowTitle("PyQt Button Click event exercise")
self.setWindowIcon(QIcon("PyQt window sample icon.png"))
btn = QPushButton("Button 1", self)
btn.move(10,10)
btn.clicked.connect(self.btn_clicked)
def btn_clicked(self):
print("Button clicked")
app = QApplication(sys.argv)
window = QtWindow()
window.show()
app.exec_()
Python source code in Github link : https://github.com/Cevastian/Python-Developer-start-today/blob/master/PyQt_Button_Event_exercise_001.py
Code run result : Type "Button clicked" text when you click the 'Button 1".