Lecture: Installing PyQt

To install PyQt, you will need Python 3.7 or higher.

To check python version type:

python3 version

To install PyQT6 on Mac:

pip3 install PyQt6

On windows:

pip install PyQt6


Lecture: Creating a simple window

import sys
#Sys is a python specific module which provides functions
# and variables which are used to manipulate different parts of Python runtime env
# sys.exit allows us to end the execution of a program.

# from the widgets module we import the Application and Wdgets
from PyQt6.QtWidgets import QApplication,QWidget

#pyqt is a library
# qtwidgets is a module, this module contains all the UI elements hence
# it is called as qtWidgets as it contains widgets
#QApplication and QWidgets are classes

#Qapplication is responsible for managing the applications main event loop,
#widget finalisation and initialisation.
# main event loop is where user inreacts with the app.

#now let's create a window using QWidget.
# hence we create a class which inherits form the Qwidget class

class Window(QWidget):

    # create a constructor
    def __init__(self):
        # super function is used to call the init method of the parent class
        # in this case, we are calling the init method of the QWidget class
        super().__init__()
        
        #set the window properties
        self.setWindowTitle("My first PyQT window")
        #set geometry methods defines the location of the window on your computer
        # and its dimensions
        self.setGeometry(100,100,400,300) # x,y,width,height
        # if you say (0,0) the window will be placed in the top left corner 
        # of the screen

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of thw window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: QLabel widget

import sys
# new code added
from PyQt6.QtWidgets import QApplication,QWidget,QLabel
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My first PyQT window")
        self.setGeometry(100,100,400,300) # x,y,width,height
				
				# label created and added
        label = QLabel(self)
        label.setText("Hello world")
				#Move method is used to arrange label on the window
        label.move(50,50)

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())


Adding an image on the window:

import sys
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QApplication,QWidget,QLabel
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My first PyQT window")
        self.setGeometry(100,100,400,300) # x,y,width,height

        label = QLabel(self)
        label.setText("This is a car")
        label.move(150,75)

        #adding an image
				#New code added
        with open('car.png'):
            image_label = QLabel(self)
            pixmap = QPixmap('car.png')
            image_label.setPixmap(pixmap)
            image_label.move(150,85)

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: Designing UI to show car details

#import the systems module
import sys
# it allows us to exit the app, quit the loop
# To create a pyqt app we need to access the class
# we can write function based code as well, but class based one is more suitable
# to create a window we need a widget, to create that widget we need to access the qwidget class

from PyQt6.QtWidgets import QWidget,QApplication,QLabel
#pywt6: package
#qtWidgets: module
# QWidget is class

# now create a class out of it so that it can create a widget for us
from PyQt6.QtGui import QPixmap,QFont

class Window(QWidget):
    # create a constructor
    
    def __init__(self):
        #we need to call the init method of the QWidget class
        super().__init__()
        # now we need to set the window properties
        # where are these methods comming from?
        # they are comming from the QWidget class
        self.setWindowTitle("My First PyQT window")
        self.setGeometry(100,100,400,400)
        #(x,y,width,height)
        
        #create the label
        label =QLabel(self)
        label.setText("This is a car")
        label.move(150,75)
        
        #creating a label to add images
        with open("audi.png"):
            image_label = QLabel(self)
            # create a qpizmap object
            pixmap = QPixmap('audi.png')
            
            image_label.setPixmap(pixmap)
            image_label.move(50,0)
            
        #car name
        name_label = QLabel(self)
        name_label.setText("My Car")
        name_label.setFont(QFont("Arial",20))
        name_label.move(170,170)
        
        #Engine specs
        engine_label = QLabel(self)
        engine_label.setText("Engine Capacity: 4L TFSI")
        engine_label.setFont(QFont("Arial",16))
        engine_label.move(20,210)
        
        #Features
        features_label = QLabel(self)
        features_label.setText("Features: ABS, EBD, ADAS")
        features_label.setFont(QFont("Arial",16))
        features_label.move(20,240)
        
        # Models
        models_label = QLabel(self)
        models_label.setText("Models: 2.2 Petrol, 1.8 Diesel")
        models_label.setFont(QFont("Arial",16))
        models_label.move(20,270)
        
        #Pricing
        pricing_label = QLabel(self)
        pricing_label.setText("$80,184")
        pricing_label.setFont(QFont("Arial",16))
        pricing_label.move(20,300)
        
# now once we have defined a class, we need to create an instance of the above class
# first we create the application's main loop

app = QApplication(sys.argv)

# create instance of the window
window = Window()

window.show()

#close the event loop
sys.exit(app.exec())


Lecture: Event handling in PyQt6

Printing text in console when button is clicked:

import sys
from PyQt6.QtGui import QPixmap,QFont
from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My first PyQT window")
        self.setGeometry(100,100,300,400) # x,y,width,height

        # new code added to create a button
        button = QPushButton(self)
        button.setText("Click me")
        button.move(100,200)
        button.clicked.connect(self.buttonClicked)
    
    def buttonClicked(self):
        print("Button is clicked")

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())

Lecture: Changing label text with events

import sys
from PyQt6.QtGui import QPixmap,QFont
from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        self.count =0
        self.setWindowTitle("My first PyQT window")
        self.setGeometry(100,100,300,400) # x,y,width,height
        # new code added to create a button
        button = QPushButton(self)
        button.setText("Click me")
        button.move(100,200)
        button.clicked.connect(self.buttonClicked)
    
        # label to display count value
        self.label = QLabel(self)
        self.label.setText("0")
        self.label.move(100,150)

    def buttonClicked(self):
        print("Button is clicked")
        self.count +=1
        self.label.setText(str(self.count))
        self.label.adjustSize()

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: Accepting input using QLineEdit widget

import sys
from PyQt6.QtGui import QPixmap,QFont
from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QLineEdit
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        
        self.setWindowTitle("My first PyQT window")
        self.setMaximumSize(300,200) #width,height
        
        name_label = QLabel(self)
        name_label.setText("Enter your name")
        name_label.move(60,10)

        self.name = QLineEdit(self)
        # sets the size of the input field
        self.name.resize(200,20)
        self.name.move(60,50)

        button = QPushButton(self)
        button.setText("Add")
        button.move(200,80)
        button.clicked.connect(self.buttonClicked)

        self.result_label = QLabel(self)
        self.result_label.setFixedSize(150,20)
        self.result_label.move(60,120)

    def buttonClicked(self):
        print("Button is clicked")
        print("Your name is:"+self.name.text())
        self.result_label.setText("Your name is: "+ self.name.text())

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: Adding two numbers

import sys

from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QLineEdit,QMainWindow
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Simple Calculator")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

        self.num1_label = QLabel("Enter first number:", self)
        self.num1_label.resize(200,20)
        self.num1_label.move(20, 20)
        self.num1_input = QLineEdit(self)
        self.num1_input.move(200, 20)

        self.num2_label = QLabel("Enter second number:", self)
        self.num2_label.resize(200,20)
        self.num2_label.move(20, 60)  # Adjusted the Y position
        self.num2_input = QLineEdit(self)
        self.num2_input.move(200, 60)  # Adjusted the X position

        self.result_label = QLabel("Result:", self)
        self.result_label.move(20, 100)  # Adjusted the Y position

        self.calculate_button = QPushButton("Calculate", self)
        self.calculate_button.move(200, 100)  # Adjusted the X position
        self.calculate_button.clicked.connect(self.calculate_sum)

    def calculate_sum(self):
        try:
            num1 = float(self.num1_input.text())
            num2 = float(self.num2_input.text())
            result = num1 + num2
            self.result_label.setText(f"Result: {result:.2f}")
        except ValueError:
            self.result_label.setText("Invalid input. Please enter numbers.")

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: QCheckbox Widget

import sys

from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QLineEdit,QMainWindow
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Simple Calculator")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

        self.num1_label = QLabel("Enter first number:", self)
        self.num1_label.resize(200,20)
        self.num1_label.move(20, 20)
        self.num1_input = QLineEdit(self)
        self.num1_input.move(200, 20)

        self.num2_label = QLabel("Enter second number:", self)
        self.num2_label.resize(200,20)
        self.num2_label.move(20, 60)  # Adjusted the Y position
        self.num2_input = QLineEdit(self)
        self.num2_input.move(200, 60)  # Adjusted the X position

        self.result_label = QLabel("Result:", self)
        self.result_label.move(20, 100)  # Adjusted the Y position

        self.calculate_button = QPushButton("Calculate", self)
        self.calculate_button.move(200, 100)  # Adjusted the X position
        self.calculate_button.clicked.connect(self.calculate_sum)

    def calculate_sum(self):
        try:
            num1 = float(self.num1_input.text())
            num2 = float(self.num2_input.text())
            result = num1 + num2
            self.result_label.setText(f"Result: {result:.2f}")
        except ValueError:
            self.result_label.setText("Invalid input. Please enter numbers.")

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: Beverage Cost Calculator

import sys

from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QCheckBox,QMainWindow
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

        # Total cost of the drink
        self.total_cost = 0

        label = QLabel(self)
        label.setText("Select your options")
        label.resize(200,20)
        label.move(20,20)

        # add checkboxes here
        sugar_checkbox = QCheckBox(self)
        sugar_checkbox.setText("Sugar ($ 0.5)")
        sugar_checkbox.move(20,40)
        sugar_checkbox.toggled.connect(self.sugar_checked)

        # add checkboxes here
        milk_checkbox = QCheckBox(self)
        milk_checkbox.setText("Sugar ($ 1)")
        milk_checkbox.move(20,60)
        milk_checkbox.toggled.connect(self.milk_checked)
        

        #label 
        self.label = QLabel(self)
        self.label.setText(str("Total cost: $0"))
        self.label.resize(200,20)
        self.label.move(20,90)

    def sugar_checked(self,checked):
        if checked:
            self.total_cost +=0.5
            self.label.setText("Total cost: $"+str(self.total_cost))
        else:
            self.total_cost -=0.5
            self.label.setText("Total cost: $"+str(self.total_cost))
    
    def milk_checked(self,checked):
        if checked:
            self.total_cost +=1
            self.label.setText("Total cost: $"+str(self.total_cost))
        else:
            self.total_cost -=1
            self.label.setText("Total cost: $"+str(self.total_cost)) 

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture QMessagebox Widget

import sys

from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QMessageBox,QMainWindow
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

        self.button = QPushButton("Show MessageBox", self)
        self.button.setGeometry(150, 80, 200, 40)
        self.button.clicked.connect(self.show_message_box)

    def show_message_box(self):
        msg = QMessageBox()
        msg.setWindowTitle("Message Box Title")
        msg.setText("This is a simple QMessageBox.")
        msg.setIcon(QMessageBox.Icon.Information)
        msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
        msg.setDefaultButton(QMessageBox.StandardButton.Ok)
        
        result = msg.exec()
        if result == QMessageBox.StandardButton.Ok:
            print("OK button clicked")
        else:
            print("Cancel button clicked")

        

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: QMessageBox for calculating square root

import sys
import math
from PyQt6.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QLineEdit,QMessageBox,QMainWindow
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

        self.number_label = QLabel("Enter a number:", self)
        self.number_label.move(20, 20)
        
        self.number_input = QLineEdit(self)
        self.number_input.move(200, 20)

        self.calculate_button = QPushButton("Find Root", self)
        self.calculate_button.move(200, 60)

        self.result_label = QLabel("Result:", self)
        self.result_label.move(20, 100)

        self.calculate_button.clicked.connect(self.calculate_square_root)

    def calculate_square_root(self):
        try:
            number = float(self.number_input.text())
            if number >= 0:
                square_root = math.sqrt(number)
                if square_root.is_integer():
                    self.result_label.setText(f"Square Root: {square_root:.4f}")
                else:
                    QMessageBox.warning(self, "Not a Perfect Square", "The number is not a perfect square.")
            else:
                QMessageBox.warning(self, "Invalid Input", "Number must be non-negative.")
        except ValueError:
            QMessageBox.warning(self, "Invalid Input", "Please enter a valid number.")

        

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: QBox layout

import sys
import math
from PyQt6.QtWidgets import QWidget,QApplication,QHBoxLayout,QLabel,QPushButton,QLineEdit,QMessageBox,QMainWindow
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

    
        label = QLabel()
        label.setText("Name")

        edit = QLineEdit()
        
        button = QPushButton("Add")

        # Create the layout and add widgets to it
        layout = QHBoxLayout()
        layout.addWidget(label)
        layout.addWidget(edit)
        layout.addWidget(button)

        # Add the above layout to our main window
        self.setLayout(layout)

    
        

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())


Lecture: Nested layout

import sys
import math
from PyQt6.QtWidgets import QVBoxLayout, QWidget,QApplication,QHBoxLayout,QLabel,QPushButton,QLineEdit,QMessageBox,QMainWindow
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

    
        button1 = QPushButton("Button 1")
        button2 = QPushButton("Button 2")
        button3 = QPushButton("Button 3")
        button4 = QPushButton("Button 4")

        hbox_1 = QHBoxLayout()
        hbox_1.addWidget(button1)
        hbox_1.addWidget(button2)

        hbox_2 = QHBoxLayout()
        hbox_2.addWidget(button3)
        hbox_2.addWidget(button4)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox_1)
        vbox.addLayout(hbox_2)

        self.setLayout(vbox)

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())



Lecture QGridLayout

import sys
import math
from PyQt6.QtWidgets import QGridLayout, QWidget,QApplication,QHBoxLayout,QLabel,QPushButton,QLineEdit,QMessageBox,QMainWindow
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Coffee Maker")
        self.setGeometry(100, 100, 400, 150)  # Increased the window width

    
        # Create widgets
        label1 = QLabel("Label 1")
        label2 = QLabel("Label 2")
        label3 = QLabel("Label 3")
        button1 = QPushButton("Button 1")
        button2 = QPushButton("Button 2")
        button3 = QPushButton("Button 3")

        # Create a grid layout and set it as the layout for the window
        layout = QGridLayout()
        self.setLayout(layout)
    
        # Add widgets to the layout at specific positions
        layout.addWidget(label1, 0, 0)
        layout.addWidget(label2, 0, 1)
        layout.addWidget(label3, 0, 2)
        layout.addWidget(button1, 1, 0)
        layout.addWidget(button2, 1, 1)
        layout.addWidget(button3, 1, 2)

# Create the application from above class
# Q application is used to manage applications resources and the event loop
app = QApplication(sys.argv)

# craete an instance of the window
window = Window()

# Show method needs to be called to show the created window on screen
window.show()

#Start the event loop, use sys.exit to close the program.
sys.exit(app.exec())