The provided text offers a comprehensive guide to building graphical user interface (GUI) applications using the PyQt framework in Python. It begins by introducing fundamental PyQt concepts like widgets, layouts (rows, columns, grids), and the framework’s modular structure. The text then progresses through building several example applications, including a random word generator, a functional calculator, an interactive photo editor leveraging the PIL library, and an expense tracker integrating SQLite databases. Each project incrementally introduces new PyQt widgets, layout management techniques, event handling, and external Python libraries. Furthermore, the material covers styling applications using CSS and explores more advanced features like data visualization with Matplotlib and implementing a dark mode. The overarching goal is to equip learners with the skills to design and develop interactive desktop applications using Python and PyQt.
Python GUI Application Development Study Guide
Quiz
- What is PyQt and what problem does it solve? PyQt is a Python binding for the Qt framework, a comprehensive C++ framework. It allows Python developers to create graphical user interfaces (GUIs) and access other features of Qt, such as database management and networking, using Python’s syntax.
- Name three of the five interactive applications that the course aims to build. The course aims to build a starter app, a calculator app, an expense tracker, an image editor (PhotoQT), and an interest rate calculator.
- Why is project-based learning emphasized in this course? Project-based learning is emphasized because it allows learners to build their skills in a way that keeps them engaged and provides a tangible final product. It also challenges learners to apply their knowledge in practical scenarios.
- What are widgets in the context of PyQt applications? Give two examples. Widgets are pre-built GUI elements that users see and interact with on an application screen. Examples of widgets include buttons (QPushButtons), text input boxes (QLineEdit), and labels (QLabel).
- What is the purpose of layouts in PyQt, and name one type of layout discussed? Layouts in PyQt are used to manage the arrangement and sizing of widgets within an application’s window, ensuring a consistent and responsive design. One type of layout discussed is the QGridLayout, which arranges widgets in a grid of rows and columns.
- Briefly explain the role of SQL in one of the course projects. In the expense tracker project, SQL is introduced to create and manage a database for storing financial transactions. PyQt is used to build the interface that interacts with this SQL database, allowing users to add, view, and delete expenses.
- What is Matplotlib, and what is its primary use in the context of this course? Matplotlib is a Python library used for data visualization. In this course, it is used in the interest rate calculator project to generate charts and graphs, providing a visual representation of the calculated interest over time.
- What is the purpose of the eval() function in the calculator app, and what potential issue does the try-except block address when using it? The eval() function in the calculator app is used to evaluate the mathematical expressions entered by the user as strings. The try-except block addresses the potential issue of errors that might occur if the user enters an invalid expression (e.g., dividing by zero), preventing the application from crashing and displaying an “error” message instead.
- Explain the concept of “events” in PyQt and how they are typically handled. Events in PyQt are signals that are emitted when something happens within the application, such as a button click or a mouse movement. They are typically handled by connecting a specific signal (e.g., clicked) of a widget to a function (a “slot”) that will be executed when that event occurs.
- What is the purpose of CSS (Cascading Style Sheets) in the context of PyQt applications? CSS in PyQt is used to style the visual appearance of application widgets, allowing developers to control aspects such as fonts, colors, backgrounds, and spacing. PyQt provides the setStyleSheet() method to apply CSS rules to widgets.
Essay Format Questions
- Discuss the advantages of using a framework like PyQt for developing desktop applications with Python compared to more basic GUI libraries. Consider factors such as functionality, cross-platform compatibility, and development workflow.
- Explain how the five different application projects in the course progressively build upon fundamental Python and PyQt concepts. Highlight specific technologies and skills introduced in each project and how they relate to the overall goal of building interactive desktop applications.
- Describe the role of data persistence in application development, and analyze how SQL is used in the expense tracker project to achieve this. Discuss the basic SQL operations demonstrated and their significance for managing application data.
- Evaluate the benefits of incorporating data visualization using Matplotlib in a desktop application. Using the interest rate calculator as an example, explain how visualizing data can enhance user understanding and interaction with the application.
- Compare and contrast the different methods of styling PyQt applications demonstrated in the course, including widget-specific methods, CSS stylesheets, and the potential for implementing features like dark mode. Discuss the flexibility and control offered by each approach.
Glossary of Key Terms
- GUI (Graphical User Interface): A type of user interface that allows users to interact with electronic devices through visual indicator representations (icons, menus) rather than text-based commands.
- Framework: A reusable body of code that provides a skeletal structure for building applications. It often includes libraries, tools, and design patterns.
- PyQt: A Python binding for the Qt framework, enabling Python developers to create cross-platform GUI applications.
- Widget: A basic building block of a GUI, such as buttons, labels, text boxes, etc., that users interact with.
- Layout: In GUI development, a mechanism to organize and manage the size and position of widgets within a window.
- Signal and Slot: A mechanism in Qt (and PyQt) for inter-object communication. A signal is emitted by an object when a particular event occurs, and a slot is a function that can be connected to a signal to be executed when the signal is emitted.
- SQL (Structured Query Language): A standard programming language used for managing and manipulating relational databases.
- Database: An organized collection of structured information, or data, typically stored electronically in a computer system.
- Matplotlib: A comprehensive library in Python for creating static, interactive, and animated visualizations in Python.
- Data Visualization: The graphical representation of information and data. By using visual elements like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends, outliers, and patterns in data.
- CSS (Cascading Style Sheets): A stylesheet language used to describe the presentation of a document written in a markup language like HTML. In PyQt, it can be used to style the appearance of widgets.
- Event: An action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Examples include button clicks, mouse movements, and key presses.
- IDE (Integrated Development Environment): A software application that provides comprehensive facilities to computer programmers for software development. VS Code (Visual Studio Code) is an example used in the course.
- Library (in programming): A collection of pre-written code that users can incorporate into their programs to perform specific tasks, saving development time and effort.
- Cross-Platform Compatibility: The ability of software to run on different operating systems (e.g., Windows, macOS, Linux) without requiring significant modifications.
- Module (in Python): A file containing Python definitions and statements. Libraries are often composed of multiple modules.
- pip (Package Installer for Python): A package management system used to install and manage software packages written in Python.
- Object (in programming): An instance of a class, which can contain data (attributes or properties) and code (methods or functions).
- Class (in programming): A blueprint for creating objects. It defines the attributes and methods that objects of that class will have.
- Method (in programming): A function that is associated with an object and can operate on the object’s data.
Briefing Document: Review of Python GUI Course Sources
Date: October 26, 2023 Prepared For: Interested Learners Prepared By: Gemini AI Assistant Subject: Detailed Review of “Building Desktop Applications with Python” Course Materials
This briefing document provides a detailed review of the main themes, important ideas, and facts presented in the provided excerpts from the “Building Desktop Applications with Python” course materials (referred to as “01.pdf”). The course aims to empower individuals with existing Python skills to develop interactive desktop applications using graphical user interfaces (GUIs).
Main Themes:
- Transitioning Python Skills to GUI Development: The core theme is to elevate existing Python knowledge by introducing the concepts and tools necessary for building desktop applications with user-friendly interfaces. The instructor emphasizes moving beyond command-line scripts to create interactive and visually appealing applications.
- Project-Based Learning: The course adopts a hands-on, project-based approach. Learners will build five distinct interactive applications throughout the 7-hour duration, reinforcing theoretical concepts with practical implementation. This allows learners to see tangible results and continuously build upon their skills.
- Introduction to Key Python GUI Technologies: The course focuses on core technologies within the Python ecosystem for GUI development. The primary framework highlighted is PyQt (specifically PyQt5), a powerful and widely used library that bridges the C++ Qt framework with Python. Additionally, the course introduces SQL for database management and Matplotlib for data visualization within the applications.
- Step-by-Step Learning and Practical Application: The instructor emphasizes breaking down complex tasks into easily understandable topics, catering to programmers of all levels. The focus is on learning by doing, with learners actively coding and designing the applications. The course structure explicitly outlines the progression from basic PyQt concepts to more advanced features like database integration and data visualization.
- Free and Accessible Learning: The course is hosted for free on the instructor’s platform, encouraging accessibility for a wider audience. The instructor emphasizes community engagement and provides additional free resources on their platform.
Most Important Ideas and Facts:
Course Overview and Structure:
- The course is a “project-based course” designed to challenge learners and provide a final product.
- “our initial overview is you can expect a project-based course as this allows you to build your skills in a way that keeps you going but also challenges you and you can see a final product”
- It aims to build a “strong foundation in the fundamental concepts of building apps in Python with pqt” while leveraging existing Python skills.
- The course will cover setting up PyQt projects, creating app widgets, designing GUIs, and adding functionality.
- Key PyQt concepts to be covered include “pqt widgets how we can create custom widgets how we can style our widgets and using buttons and labels within our programs.”
- The curriculum progresses from basic PyQt application creation and layout management to integrating “SQL to create databases in pqt” and finally “data visualization with a module called matap plot lip.”
- Learners will work through five projects: a starter app, a calculator app, an expense tracker, an image editor (“photo QT”), and an interest rate calculator.
- The course is designed for “programmers of all levels,” those looking to grow their Python portfolio, project-based learners, and visual learners.
- Access to “all my slides live coding projects and more” will be provided.
Software Setup and Libraries:
- The course utilizes Visual Studio Code (VS Code) as the Integrated Development Environment (IDE).
- The recommended Python extension for VS Code is simply “Python.”
- The instructor uses the “synth wave 84” theme in VS Code, which learners can optionally adopt for visual consistency.
- Three primary Python libraries will be used throughout the course:
- PyQt5: For building the graphical user interfaces.
- “we are going to be using pqt”
- Pillow: Likely for image manipulation within the image editor application.
- “we are going to be using pillow”
- Matplotlib: For creating charts and graphs in the interest rate calculator.
- “we are going to be using Matt plot lib”
- Instructions are provided for installing these libraries using pip3 install <library_name> or python3 -m pip install <library_name>.
Introduction to PyQt:
- PyQt acts as a “module that Bridges it it connects a popular framework in C++ and python,” allowing developers to use the Qt framework in Python.
- It enables the creation of “graphical user interfaces” (GUIs).
- PyQt offers capabilities beyond just visual elements, including “creating data bases with SQL or adding in embedded web browsers.”
- A “widget is what you see on the app screen,” representing individual GUI elements like buttons and text inputs.
- “a widget is what you see on the app screen”
- The course will focus on PyQt5, with the explanation that it is very similar to PyQt6, and knowledge of PyQt5 provides compatibility with a wider range of applications.
- “there is no major difference between these two in this course we will specifically focus on pi qt5 as these two versions the framework are so similar”
- Reasons for choosing PyQt include:
- Cross-platform compatibility: Apps can run on Windows, macOS, and Linux.
- “pqt allows for crossplatform compatibility so it allows our apps to be run on different operating systems”
- Endless widgets: Provides a wide variety of pre-built GUI elements.
- “it also provides endless widgets… pqt provides these ready-made or pre-built GUI elements”
- Wide range of components: Beyond basic widgets, it includes support for databases, graphics, and networking.
- QT Designer: A visual tool for building GUIs (although the course will focus on programmatic creation).
- “QT designer makes it significantly easier to build a pi QT app it’s kind of like figma or canva for building with pqt we won’t be addressing that in this course because that’s not programming that’s not coding that’s not learning the logic”
- Python-based: Leveraging Python’s easier syntax.
- “pqt is based in Python py right we are bridging it and connecting it to python which makes it very straightforward to us as python is an easier language and has easier syntax to understand”
Window Applications and Layouts:
- PyQt is designed to create “window applications,” which are standalone programs with their own windows.
- “pqt is made to create these window applications”
- A window application consists of a “main window” that acts as a container for “app Widgets or objects.”
- “we have a main window and inside this main window we have app Widgets or objects”
- Widgets are GUI elements like “text input box a checkbox text push buttons a list.”
- “Layouts” in PyQt are used to structure and organize the widgets within the application window.
- “We use layouts in pi QT to build out our design”
- Examples of layouts include rows and columns, and PyQt provides layout classes to implement these designs.
- Widgets are added to layouts by specifying their row and column position in a grid-based system (starting from index 0).
Calculator App Development (Initial Stages):
- The initial design of the calculator app aims for a layout with a text input area (using QLineEdit) at the top and a grid of buttons below (using QPushButton).
- PyQt widgets to be used include QApplication, QWidget, QLineEdit, QPushButton, QHBoxLayout, QVBoxLayout, and QGridLayout.
- The basic template for a PyQt application involves creating a QApplication instance, a main window (QWidget), setting its title and initial size, showing the main window, and executing the application.
- Repetitive button creation can be handled efficiently using loops in Python.
- “Loops what are the two types of Loops you know in Python the while loop and the for Loop. The four Loop is used to iterate to go through something else. Let me propose that we actually Loop through to create our grid”
- A list of button labels can be iterated through to create QPushButton objects and add them to the QGridLayout.
- Counter variables can be used within loops to manage the row and column placement of buttons in the grid.
Next Steps (Implied):
The excerpts lay the groundwork for building interactive desktop applications with Python and PyQt. The subsequent parts of the course will likely delve into:
- Implementing functionality for the calculator app (button clicks, calculations).
- Developing the image editor (image loading, editing operations using Pillow).
- Building the expense tracker (database creation with SQL, data entry, and display).
- Creating the interest rate calculator (data visualization using Matplotlib).
- Styling the applications using CSS within PyQt.
This briefing document highlights the key information presented in the initial course materials, setting the stage for learners to embark on their journey of building desktop applications with Python GUIs.
Python Desktop Apps: PyQt GUI Development
Frequently Asked Questions about Building Desktop Applications with Python
1. What will I learn in this Python GUI course? This course will guide you through building five interactive desktop applications using Python. You’ll learn to create graphical user interfaces (GUIs) using the PyQt framework, work with databases using SQL, and perform data visualization with Matplotlib. The course covers fundamental concepts of building Python apps with PyQt, including setting up projects, creating and designing widgets, implementing application functionality, styling with CSS, and more.
2. Who is this course designed for? This course is designed for programmers of all levels who want to elevate their Python skills and learn how to build desktop applications with graphical user interfaces. It’s particularly beneficial for those looking to expand their Python portfolio, visual learners, and individuals who appreciate complex tasks broken down into easily understandable concepts. Basic Python understanding is recommended as PyQt is a class-based framework.
3. What are the key technologies and libraries used in this course? The core technologies and libraries you will explore in this course include: * PyQt5: A powerful Python framework for creating graphical user interfaces. * SQL: For creating and interacting with databases within your applications. * Matplotlib: A Python library used for data visualization, allowing you to create charts and graphs. * Pillow (PIL): A library introduced for image manipulation in one of the projects.
4. What kind of projects will I build in this course? Over the course, you will build five interactive applications: * A starter app to get familiar with the initial setup and design in PyQt. * A calculator app with added styling. * An image editing application (PhotoQT) that allows editing real photos in Python. * An expense tracker application that incorporates database creation using SQL. * An interest rate calculator with data visualization using Matplotlib.
5. Why is PyQt chosen as the GUI framework for this course? PyQt is a popular choice for building Python GUIs due to several reasons: * Cross-platform compatibility: Apps built with PyQt can run on various operating systems (Windows, macOS, Linux). * Extensive widgets: PyQt provides a wide range of pre-built GUI elements (buttons, text inputs, menus, etc.). * Rich functionality: Beyond basic widgets, PyQt offers features for database integration, graphics, networking, and more. * Python-friendly: As a Python binding for the Qt C++ framework, it leverages Python’s straightforward syntax. * While PyQt offers a visual designer (Qt Designer), this course focuses on building UIs through code to enhance understanding of the underlying logic.
6. How will databases be integrated into the applications? The course introduces SQL for creating and managing databases within your PyQt applications. You will learn the basics of SQL, such as creating tables and performing queries, without needing prior SQL experience. One of the capstone projects, the expense tracker, specifically focuses on using SQL to create a database for storing and managing financial transactions. You’ll learn how to connect to a SQLite database using PyQt’s QtSql module, execute SQL queries to create tables, insert data, retrieve data, and delete data based on user interaction.
7. What will I learn about data visualization with Matplotlib? The course introduces Matplotlib for data analysis and visualization within Python applications. You will learn how to use Matplotlib to create charts and graphs to represent data. The interest rate calculator project culminates in using Matplotlib to visualize interest rate calculations over time. You’ll learn how to create figures, subplots, plot data, and customize your charts with titles and labels. The integration of Matplotlib with PyQt is facilitated using the FigureCanvasQt class from Matplotlib’s backends, allowing you to embed Matplotlib charts within your PyQt GUI.
8. Will I learn about styling my Python desktop applications? Yes, the course covers styling Python desktop applications using a few different approaches. For the calculator app, you’ll learn to customize the appearance of widgets using PyQt’s functionalities, such as setting fonts. Later, the course introduces Cascading Style Sheets (CSS) for more comprehensive styling, similar to web development. You’ll learn how to use the setStyleSheet method in PyQt to apply CSS rules to your application’s widgets, allowing you to control colors, fonts, spacing, and other visual aspects. Finally, the course explores implementing a dark mode as an advanced styling feature, toggling between different stylesheets based on user preference.
PyQt Widgets: Building Blocks of GUI Applications
Based on the sources, QT widgets are fundamental building blocks for creating graphical user interfaces (GUIs) in Python using the PyQt framework.
Here’s a comprehensive overview of QT widgets as discussed in the sources:
- Definition: A widget is any element you see on an application’s screen. This includes buttons, text labels, input fields, menus, and more. The PyQt5.QtWidgets module provides a collection of these pre-built GUI elements or objects that can be added to your application.
- Purpose: QT widgets enable you to create interactive and visually appealing desktop applications. They provide the user interface components that allow users to interact with your Python programs.
- Key Concepts:
- Framework Module: PyQt is a comprehensive framework, and QtWidgets is one of its modules containing various widget classes.
- Class-Based: PyQt is a class-based framework, meaning you work with classes to create and manage widgets. Each widget you use is typically an instance of a specific widget class.
- Objects: When you use a widget class, you create an object or an instance of that class, which you then manipulate and display in your application.
- Essential Widgets:
- QApplication: This is a crucial class that allows you to create and execute your PyQt application. Every PyQt application must have one instance of QApplication.
- QWidget: This serves as the basic building block for all user interface objects. It provides the main window for your application where other widgets are placed. Your custom application windows often inherit from QWidget.
- Commonly Used Widgets (with examples from the course projects):
- QLabel: Used to display text or images on the screen. In the example app, QLabel is used for the title and random words. In the image editor and interest rate calculator, it’s used as a placeholder for the image/chart initially.
- QPushButton: Represents a clickable button that can trigger actions when clicked. Used for actions like “submit” in the example app, number and operation buttons in the calculator, editing tools in the image editor, and “Add Expense,” “Delete,” “Calculate,” and “Clear” buttons in other applications.
- QLineEdit: Provides a text input field where users can enter and edit single-line text. Used for entering expressions in the calculator, amount and description in the expense tracker, and interest rate, initial investment, and years in the interest rate calculator.
- QVBoxLayout and QHBoxLayout: These are layout managers that help you organize and arrange widgets in your application either vertically (QVBoxLayout) or horizontally (QHBoxLayout). They automatically handle the sizing and positioning of the widgets they contain.
- QGridLayout: Another layout manager that arranges widgets in a grid (rows and columns). Particularly useful for structured layouts like the calculator’s button pad.
- QListWidget: Displays a list of items that the user can select. Used in the image editor to show the list of files in a selected folder.
- QComboBox: Creates a drop-down list (combo box) from which users can select an option. Used in the image editor for applying filters and in the expense tracker for selecting categories.
- QDateEdit: Provides a widget for selecting dates. Used in the expense tracker to input the date of the expense.
- QTableWidget: Displays data in a table format with rows and columns. Used in the expense tracker to show the list of expenses. Methods like setColumnCount and setHorizontalHeaderLabels are used to configure the table.
- QTreeView: Presents data in a hierarchical tree structure. Used in the interest rate calculator to display the year and total interest calculated. It uses a QStandardItemModel to manage the data displayed in the tree.
- Widget Manipulation:
- Creation: Widgets are created by instantiating their respective classes (e.g., QLabel(), QPushButton(“Click Me”)).
- Adding to Layouts: Once created, widgets need to be added to layout managers using methods like addWidget(). Layouts then need to be set on the main window (or other container widgets) using the setLayout() method.
- Styling: Widgets can be styled to customize their appearance. This can be done through methods like setStyleSheet(), which allows applying CSS-like styles. You can target specific widget types (e.g., QPushButton, QLabel) in your style sheets. Fonts can be customized using QFont and the setFont() method.
- Functionality: Widgets can be made interactive by connecting their signals (like a button’s clicked signal) to functions (slots) that define the desired behavior.
In summary, QT widgets are the visible and interactive elements that constitute the user interface of a PyQt application. The QtWidgets module offers a rich set of pre-built widgets that can be arranged using layout managers and styled to create various desktop applications, as demonstrated through the different projects outlined in the sources.
Pillow: Python Image Manipulation Fundamentals
Based on the sources, the Pillow module, also known as the Python Imaging Library (PIL), is a crucial component for building the interactive photo editing app in Python within this course.
Here’s a comprehensive discussion of the Pillow module as described in the sources:
- Purpose: The Pillow module is specifically used to work with images in Python, allowing you to open, edit, and save them. It provides the necessary tools to implement image manipulation functionalities in your applications.
- Installation: The sources mention that Pillow needs to be installed using the Python package installer, pip. The commands provided are pip 3 install pillow or, if that doesn’t work, python 3 -m pip install pillow. This step is essential before you can use the Pillow library in your Python projects.
- Key Submodules and Classes: The sources highlight several important parts of the Pillow library that are used in the image editing app:
- Image Module/Class: This is fundamental for opening image files using Image.open(full_name), displaying images using image.show(), creating copies using image.copy(), and saving images using image.save(full_name). The Image class also provides methods for image transformations such as flipping using image.transpose(Image.FLIP_LEFT_RIGHT) and rotating using image.transpose(Image.ROTATE_90).
- ImageFilter Module: This module allows you to apply various filters to images. Examples mentioned include ImageFilter.SHARPEN and ImageFilter.BLUR, which can be applied to an image object using the filter() method (e.g., self.image.filter(ImageFilter.SHARPEN)).
- ImageEnhance Module: This module provides classes to adjust image characteristics like color, contrast, and sharpness. For instance, the ImageEnhance.Color(pick).enhance(1.2) class and its enhance() method can be used to increase the saturation of an image. Similarly, ImageEnhance.Contrast(self.image).enhance(1.5) can be used to increase the contrast.
- Basic Image Operations:
- Opening Images: Similar to opening text files with Python’s built-in open() function, you can use Image.open() from the Pillow library to load image files. You need to provide the path to the image file as an argument.
- Saving Images: The save() method of an Image object allows you to save the modified image to a file, specifying the filename and format.
- Image Manipulation Techniques Discussed:
- Converting to Black and White: The convert(‘L’) method of an Image object can be used to transform a color image into a grayscale (black and white) image.
- Applying Filters: The filter() method, along with filters from the ImageFilter module, can be used to enhance or modify the image.
- Enhancing Image Properties: Classes from the ImageEnhance module allow for adjustments to color saturation, contrast, and potentially other properties.
- Flipping and Rotating: The transpose() method with constants like Image.FLIP_LEFT_RIGHT and Image.ROTATE_90 can be used for geometric transformations.
- Integration with PyQt: The Pillow module is used in conjunction with PyQt to build the image editing application. After loading and editing images using Pillow, the resulting image data needs to be displayed in the PyQt application’s GUI. The sources mention using QPixmap (from PyQt5.QtGui) to handle image display within PyQt.
- Importance of Specific Imports: The sources emphasize the best practice of importing specific classes and modules from Pillow (e.g., from PIL import Image, ImageFilter, ImageEnhance) rather than using a wildcard import (from PIL import *), as Pillow is a large library.
In summary, the Pillow module is essential for the image editing project, providing the functionality to load, manipulate through various filters and enhancements, and save image files within the Python application built with PyQt.
PyQt and SQL for Desktop Applications
Based on the sources, SQL databases are a key technology explored in this course for building interactive desktop applications with Python and PyQt, particularly within the expense tracker application.
Here’s a breakdown of the discussion around SQL databases in the sources:
- Purpose: SQL is used to create and manage relational databases within the PyQt applications. These databases allow for the storage and retrieval of structured data in tables. In the context of the expense tracker, SQL is used to store information about expenses, such as date, category, amount, and description.
- Integration with PyQt: PyQt provides specific modules and classes to interact with SQL databases. The primary modules involved are:
- PyQt5.QtSql.QSqlDatabase: This class is used to establish a connection to a SQL database. The course specifically focuses on SQLite databases due to their lightweight nature and ease of use within Python applications. The addDatabase() method is used to create a database connection, setDatabaseName() to specify the name of the database file (e.g., expense.db), and open() to open an existing database file, ensuring that previously stored data is loaded when the app starts. Error handling is implemented to check if the database can be opened, and if not, a critical error message is displayed, and the application may exit.
- PyQt5.QtSql.QSqlQuery: This class is used to execute SQL queries on the connected database. Queries are essentially questions or commands sent to the database to perform actions like creating tables, inserting data, selecting data, and deleting data. The execute() method runs the SQL query. For safer data insertion, especially when dealing with user input, the prepare() method is used to prepare a SQL query with placeholders, and then addBindValue() is used to securely bind the actual data to these placeholders, preventing SQL injection vulnerabilities.
- Database Schema and Table Creation: In the expense tracker, an initial query is executed to create a table named expenses if it doesn’t already exist. The CREATE TABLE IF NOT EXISTS SQL command is used for this purpose. The expenses table is defined with several columns, each with a specific data type:
- ID: An integer that serves as the primary key for each expense entry and is set to auto-increment, meaning the database automatically assigns a unique ID to each new entry.
- date: Stores the date of the expense as text.
- category: Stores the category of the expense as text.
- amount: Stores the monetary amount of the expense as a real number.
- description: Stores a description of the expense as text.
- Data Manipulation:
- Inserting Data: When a user adds a new expense, the application retrieves the data from the input fields and uses an INSERT INTO SQL query to add a new row into the expenses table. Placeholders are used for the values (date, category, amount, description), and addBindValue() is used to associate the actual data with these placeholders before the query is executed.
- Selecting Data: To display the existing expenses in the QTableWidget, a SELECT * FROM expenses SQL query is used to retrieve all data from the expenses table. The results are then iterated through, and each row from the database is inserted as a new row in the QTableWidget, with each column’s value from the database being placed into the corresponding cell of the table. The value() method of QSqlQuery is used to retrieve the data from each column of the current row in the database result.
- Deleting Data: When a user wants to delete an expense, the application first identifies the ID of the selected row in the QTableWidget. A DELETE FROM expenses WHERE ID = :id SQL query is then prepared, where :id is a placeholder. The ID of the selected expense is bound to this placeholder using addBindValue(), and the query is executed to remove the corresponding row from the expenses table.
- GUI Integration (Expense Tracker): The data from the SQL database is visually represented in the expense tracker application using a QTableWidget. The setColumnCount() and setHorizontalHeaderLabels() methods of QTableWidget are used to define the number of columns and their respective names, mirroring the structure of the expenses table in the database. The insertRow() method adds new rows to the table, and setItem() along with QTableWidgetItem is used to populate the cells of the table with the data retrieved from the database. When an expense is deleted, the corresponding row is removed from the database, and the loadTable() method is called to refresh the QTableWidget with the updated data.
In essence, SQL databases provide a persistent storage mechanism for the PyQt applications, allowing them to save and retrieve data even after the application is closed and reopened. PyQt offers the necessary tools to seamlessly integrate with SQL databases, enabling the creation of data-driven desktop applications.
PyQt Applications: Styling with CSS
Based on the sources, CSS styling is a method used in this course to enhance the visual appearance of the PyQt desktop applications.
Here’s a comprehensive discussion of CSS styling as described in the sources:
- What is CSS? CSS, which stands for Cascading Styling Sheets, is a language primarily used to style websites, working in conjunction with HTML and JavaScript. However, the sources explicitly state that CSS can also be used with other languages, including Python and its GUI framework, PyQt.
- How it Works in PyQt: In PyQt, CSS styling is applied to widgets using the setStyleSheet() method. This method accepts a string as an argument, and this string contains the CSS rules that you want to apply to the widget.
- CSS Syntax in PyQt: The CSS syntax used within the setStyleSheet() method in PyQt is very similar to standard CSS used for web development. It involves targeting specific elements (widgets) and then defining style properties within curly braces {}.
- Targeting Elements (Widgets): You can target different types of PyQt widgets by using their class names directly. Examples from the sources include:
- QWidget: To style the entire application or main window.
- QLabel: To style text labels.
- QLineEdit: To style input fields.
- QPushButton: To style buttons.
- QTreeView: To style tree view widgets.
- QTableWidget: To style table widgets.
- QComboBox: To style combo (dropdown) boxes.
- QDateEdit: To style date edit controls.
- Style Properties: Within the curly braces, you define style properties using a key-value pair format, separated by a colon : and terminated by a semicolon ;. Examples of CSS properties used in the sources include:
- background-color: To set the background color of a widget.
- font-size: To set the size of the font.
- font-family: To set the typeface of the font.
- padding: To add spacing around the content of a widget.
- border: To add a border around a widget.
- color: To set the text color.
- Applying Styles: The setStyleSheet() method is called on a specific widget instance to apply the defined styles to that widget. You can apply global styles by setting the style sheet on the main QWidget or more specific styles to individual widgets.
- Targeting States (e.g., Hover): PyQt’s setStyleSheet() also allows you to target specific states of widgets using pseudo-classes, similar to CSS in web development. The source provides an example of the :hover state for QPushButton to change the button’s appearance when the mouse cursor is over it.
- Organization of Styles: The sources demonstrate different ways to organize CSS styling:
- Directly within the setStyleSheet() method call.
- Using multi-line strings (with triple quotes “””) for better readability when defining multiple styles.
- Creating a separate method (e.g., applyStyles()) within a class to encapsulate all the styling logic, which can then be called during initialization or in response to events (like toggling dark mode).
- Dark Mode Implementation: The implementation of a dark mode in the interest rate calculator application heavily relies on CSS styling. By checking the state of a QCheckBox, different sets of CSS rules are applied using setStyleSheet() to switch between a light and a dark theme by altering background colors and text colors of various widgets.
In summary, CSS styling in PyQt, applied via the setStyleSheet() method, offers a powerful and flexible way to customize the look and feel of your desktop applications by leveraging familiar CSS syntax to target widgets and define their visual properties.
The Original Text
are you ready to start building your own desktop applications you’ve landed on the Right video this is the course for you over the next 7 hours we are going to be building five interactive applications with python this course is designed for those wanting to take their python skills up a level and Learn Python guis or graphical user interfaces you’re going to be exploring core Technologies in Python like the powerful High QT framework and SQL and Matt plot lip just to name a few well without further Ado I don’t want to keep you guys waiting let’s start building apps it’s why you’re here are you ready cuz I’m ready let’s dive in welcome guys to another code with Josh special for super obvious reasons I’m Josh if you guys don’t want to hear me ramble on for the next few minutes it is going to be beneficial here’s the time stamp that just jumps into the course you can check that out okay but as I mentioned we’re going to be building five interactive apps a starter app a calculator app expense tracker an image editor as well as an interest rate calculator using matplot lib SQL guys this course is hosted absolutely free right show some love smash that like button and subscribe comment and engage as that does help my course reach more students around the world okay that is is your way you can show support and guys the first link in the description won use the links okay but I’m hosting this course on my own platform for you guys absolutely free over there’s the community all my other free resources all right so to show your support just use the links in the description all right um okay enough chitchat uh let’s just jump into the course I’m really excited I hope you are too [Music] hi there and Welcome to our course before we get started I like to kick off my courses by going over the course structure and what you can expect in this course let’s jump in and let’s take a look our initial overview is you can expect a project-based course as this allows you to build your skills in a way that keeps you going but also challenges you and you can see a final product you will be building a strong foundation in the fundamental concepts of building apps in Python with pqt and you will use your existing python skills now you should have a basic understanding as this course and pqt is a class-based framework the knowledge you gain from this course will be key in your programming journey and allow you to expand on what you already know we are going to talk about the setup for any pqt project we will look at ways to create our app widgets design our GUI and add some app functionality throughout this course we will talk about pqt widgets how we can create custom widgets how we can style our widgets and using buttons and labels within our programs to break down our course overall we will begin with giving you a good understanding of how we use pqt to create applications we then build on working with layouts in designs for our overall apps while introducing widgets and creating interactive guis once you’ve built this solid foundation of creating your layouts working with widgets we now have a basic understanding of pqt you will then be introduced to SQL and how we can use SQL to create databases in pqt now we’re only brushing the surface here and you don’t need to have any background in SQL you’ll learn everything you need to know here to hit the ground running and for our final project you will learn data visualization with a module called matap plot lip this will introduce you to data analysis and data visualization with python you’ll also see how we can use CSS to style our python applications throughout this course you will have five projects in total the first project isn’t here but it’s a project to get you warmed up with the initial setup and the design for pqt then we work with four projects that all build upon each other our first one is going to be a calculator app and we will add styling to this app we then move on to an image editing application or I’ve nicknamed my app photo QT this app allows you to edit real photos in Python we then will progress into our third Capstone project this is an expense tracker and here is where you’ll learn how to create a database using SQL our final project is going to be an interest rate calculator with our data visualization this is where we will talk about how we can use charts and graphs in our applications who is this course designed for well it’s designed for a lot of you it’s designed for programmers of all levels for those looking to grow their python portfolio those looking who want complex tasks broken down to a basic level of understanding that is what my courses in the zero to knowing series does breaks down complex tasks into easily understandable topics this this course is designed for project-based Learners as well as all you visual Learners out there don’t worry you’ll get access to all my slides live coding projects and more now that you have an overall understanding of what you can expect in this course and the overall structure let’s jump in and let’s start off with the installation of what we need to hit the ground running I’ll see you guys in the next video [Music] all right we’re just about there before we jump into the first lesson I want to get everything installed and set up here within vscode now you may have already used vs code or this might be new to you let’s go through just one extension that we’re going to be using and I’ll give you mine as well the first extension that you should have please look for Python and just go through and make sure that you do have python within VSS code you can install this here I am using a theme as you can see here we have a few different things going on now if you want to to follow along with my theme cuzz color coordination works for me it might work for you I use synth wave 84 as my theme currently for the duration of this course you are welcome to get it there too okay let’s get that out of the way we have looked at our two extensions now going forward we are going to be working with a few different libraries throughout this course I want to install them all right now so I have them we are going to be using pqt we are going to be using pillow and we are going to be using Matt plot lib let’s get these all installed to open your terminal on a Mac you can press command J or on a Windows control J down here I just want to install so using the python package installer I’m going to say pip 3 for yours you might say p pip but with most updated newer versions of python pip 3 seems to be the way to go I’m going to say pip 3 install Pi qt5 enter let it do its thing now as you can see it says requirement already satisfied for mine that’s because I already have it here for the pillow Library I’m going to say pip 3 install pillow get that there now if none of these are working for you okay you may need to try python 3-m pip install pillow you can try using instead of pip 3 saying Python 3 this brings us to our final one which is mat plot lib so pip three install Matt plot lib as you can see I also have that one already installed at this point you’re ready to go you have pqt framework installed which we will be using for our course and then we will also introduce how to use pill in the pillow Library as well as Matt plot lib at later stages I’m ready for the first lesson and at this point you are too I’ll see you guys in lesson one of our [Music] course hi and welcome to the zero to knowing building apps in Python course in this course we will be looking at how to create apps in Python using the pqt framework before building any apps let’s jump in and let’s talk about what is pqt so long story short pqt is a module that Bridges it it connects a popular framework in C++ and python so it allows us to use this popular C++ framework in the language we choose to use which is Python and it enables us to create graphical user interfaces now you’re going to hear this a lot throughout this course and what you’re going to hear me say is you’re going to hear me say GUI GUI is a reference for graphical user in interfaces pqt it allows us to do many different things such as creating data bases with SQL or adding in embedded web browsers and even using its own collection of widgets and a widget is what you see on the app screen and there’s so much more that we can do with pqt and these features make QT a comprehensive of framework and it allows us to make all types of apps in Python let’s talk about what is the difference between pi qt5 and Pi qt6 well there is no major difference between these two in this course we will specifically focus on pi qt5 as these two versions the framework are so similar anything you do in pi qt5 that are easy workarounds to any solutions that may occur with pi qt6 and by learning and understanding just the last version pyqt5 you’re going to be able to work with a wider range of applications you’ll be able to work with older pqt apps as well as the new apps using pqt 6 the final question you may be asking yourselves now is why do we use pqt why do developers choose this framework over others I’ve put together a few popular reasons why going through them pqt allows for crossplatform compatibility so it allows our apps to be run on different operating systems like I am on a Mac but you yourself may be on a Windows or a Linux pqt allows for this it also provides endless widgets you’re going to hear this a lot in our course what is a widget a widget is something you see on your app screen it could be buttons text menus anything like that and pqt provides these ready-made or pre-built GUI elements they also offer a wide range Beyond just these components like I’ve mentioned in the previous slides we could include databases Graphics like pictures networking and a few of these we will actually be building projects in this course using them pqt also has something called QT designer and QT designer makes it significantly easier to build a pi QT app it’s kind of like figma or canva for building with pqt we won’t be addressing that in this course because that’s not programming that’s not coding that’s not learning the logic in this course most developers aren’t going to use QT designer you’re expected to know how to build out an app and what things are doing within your app that’s what we focus on here finally pqt is based in Python py right we are bridging it and connecting it to python which makes it very straightforward to us as python is an easier language and has easier syntax to understand now that we understand what pqt is and why we use it let’s head over into our next video and talk about window applications I’ll see you guys in the next video [Music] here we are at the introduction to our first app before we start making our first app we need to understand what is a window application and pqt is made to create these window applications we are here to touch on the foundations we will use to construct and build your first app these are two current and popular examples of window applications I took these off my Mac and you see a calculator and we have the system preferences tab they pop out when we need them and we close them when we do not need them anymore more as we break this down further let’s examine and take a look at the system preferences app that you see here on the left we have a main window and inside this main window we have app Widgets or objects these work together to create the GUI of our app and if you think about the main window as like a jar right and then all of the widgets are the coins and the money inside the jar they all represent something different but they’re all inside the same jar this jar is like the parent it’s like the main window of our app within the app you also see many widgets which is a word that I also keep using in this app we see a text input box a checkbox text push buttons a list all of these are a type of widget or an object that we create and then we later add into the app remember this word later but these are widgets from a class called QT widgets if I asked you to design this app what comes to mind what type of layout would you use would you draw this out would you you put it in rows how could we design it that’s a great question and as we start looking further at apps it’s a question that you should be asking yourself how I would design this app is yes rows and columns exactly what can we store in a row and what can I store in a column can I store columns in a row let’s look at that this has two rows and two columns we use layouts in pi QT to build out our design okay widgets they are automatically aligned either vertically or horizontally so my two rows are horizontal and my two columns are vertical in row one I have 1 two three four buttons they’re in their own row at the top of my app in the second row I actually have two columns one column two column with some text and a button these columns are added into a row at the end interesting so start thinking about how can we break an app down to the design basics of rows and columns moving forward let’s take a look at what exactly the pqt framework is and how it all ties together pqt is a massive framework and within this framework we have modules so for example you may have used other popular python modules like the built-in ones time and random or maybe you’ve used other external modules Frameworks like pandis or plotly or others like that well pqt is like that it is one main framework and then within that there are many modules within each module there are many classes many functions all of that stuff here I’ve put just a few of the popular pqt modules will we use all of these in our course no will we use some of them absolutely are there going to be others also yes there will be others these these are just a few popular ones starting off I’m going to talk about QT widgets because we actually saw this earlier remember everything on the app screen is considered a widget and this really provides us with GUI elements or objects that we can add into our app screen another module that we will start off with using early on is a module called QT core QT core essentially holds the miscellaneous elements that we need within certain elements of our app as we grow in our fundamentals and understanding of app development you can expect to learn a little bit of sequel in this course in creating databases as well as learning some GUI and design elements something that I’ve created that I love to teach the order of in this pattern is the code Burger all right I’m going to put this at stages throughout this course if you take notes which not really if you should be taking notes and if you do you should write this down or screenshot the code Burger this is the order of steps we must take in order to design an app in pqt and get it to open and run accordingly number one we need to make sure all of our Imports are at the top of our burger at the top of the coat once we import everything we need I will then create my main app objects and all my app settings like the size of my app the title of my app things like that once we get everything set up I can then create all the widgets that I want to have in my app they can be stored at the top all the buttons all the text anything like that can be stored in this step once we create all these widgets we need to add them to our design we need to design our app or design our layout and add all those widgets to the main window our screen once we finalize that design it’s the good idea to set our final layout we want to set the final design to our main window ending with showing and executing our app pqt is a class-based language now at this point in your programming Journey you should understand the fundamental concepts of python and programming in general python has a core concept of objectoriented programming that is where we create objects in classes and the class can store fundamental information about those objects if we do a quick class flashback pause the video read through this code and understand what’s happening do you understand everything what things do you not quite understand and then answer the question for me what is a method and what is a property all right to touch on these very briefly we defined a class called app remember a class name is one of the only things in Python that is capitalized ized my class is called app I have three methods 1 2 3 a method is a function in a class I then create an object the value of an object is a class in this case is app I’m giving app three arguments one two 3 because my app has one two three parameters these parameters are used as the value to my properties what is a property a property is a variable in a class I can then use these throughout parts of my class when it comes time to use a method a method must be linked to your object so a method is a function in a class you must link it to an object of that class in order to use it all right that was a lot but don’t worry because I’ve color coordinated a part of it and I want you to take a look at that now making an object we’re giving the three arguments to our class now these arguments we are giving to init in it is what we call our Constructor method Constructor construction build we use in it to build our class now pqt is a framework that has modules each module has classes these classes we can import into our projects to allow us to use them in our apps each class has methods and properties of its own that we can use when we link it to an object of that class that’s a lot but this flashback it should get the gears turning it should bring back memories in The Core Concepts of how we use objectoriented programming in Python brilliant let’s talk about how we can connect 2 pi QT to set app up remember step number one of the code Burger we want to import everything we need now pqt you can see I am linking to one of the modules pqt is the framework QT core and QT widgets are a module from our framework QT is a class from my module QT core I am importing some something called QT you’ll find out more about this very soon then we import all of the QT widgets we need these widgets are the objects that we want to see within our app do you want to see buttons do you want to see an input field text what do you want to see in your app that’s what we import here the two most important classes that we must Import in order to get a working app our Q application and Q widget Q application it allows us to create and execute our app Q widget on the other hand allows us to actually create that main window the parent that all the other objects are dropped into great we need those two that’s why I always like to import them first next is anything you want to see in your app anytime you want to see text on the screen of your app text in pqt is called a q label anytime you want a submit style button that is called a q push button that’s like a click button or submit button and then the other one we’re going to take a look at here you visibly cannot see this but for the design of our app we need to use layouts now what we’re going to be looking at in this first app is a vertical layout V and we will also be looking at a horizontal layout these give our app alignment in the case of QV box layout this is going to be vertical alignment we have just introduced a few classes that come with QT core and QT widgets remember QT widgets provides us the GUI elements the widgets or the objects you want to see on the screen of your app in QT core it kind of contains some miscellaneous things that we can use throughout our programs mainly for us what we are going to be using is the QT tool for alignment like align left align right align Center to help us structure our app in a more visually appealing way we’re getting super close to starting to code but before we do I’ve just introduced some important classes that we will be importing but we need to talk about a few of those important methods you’re going to be using with these classes what is a method remember it is a function in a class what is a property a variable in a class how do we use them a method in property must be linked to an object in order to work let’s take a look at some popular ones we will start off with today in order to add an object to our screen we use the method add widget this allows us to add our object specifically to a layout so to a column or a row we can change or set the text of an existing object by using the set text method remember this for later change the text of something that’s where it’s really useful when we want to add two layouts together we cannot use add widget because a layout is not a widget in order to add a column to a row for example we can use add layout and this adds two layouts together once we have one final Master layout where everything is held we can take that Master layout and we can set that as the final layout to the main window here is the method we can use to set the final design to our main window our last two methods we will use throughout our course is show and hide and this allows you to show or hide an object when something happens let’s take a look at your first app that we’re about to put together this is our first application it’s rather basic but it does everything we want it to do to hit the ground running and and understand the fundamentals it allows us to add objects on the screen we will be creating functions as well as programming these buttons to do something so let’s get comfortable with the foundations of app design in pqt 5 what do we see here so I have a main window I have like a title text I have some text for some random words and then I have clickable buttons can you locate them here they are now I want you to think about I introduced important classes that we will import earlier what classes will we need to import in order to build this app I want you to think about that well in order to create our main window our main window uses the class Q widget any text on the screen is known as a q label one two three four I will have four Q label objects and then a submit style button is known as a q push button you may be noticing two things one everything starts with Q yes that’s true also everything is camel cased camel casing means it’s one word but every word the first letter is capitalized that is very important if you spell one of these wrong you’re going to get an error and it’s going to say undefined next up how will you design the app how can we solve this what design elements should we think about here you can pause try and use those Clues to help you it’s not completed yet what we could do is we could start with three rows that’s the most basic form of design design in this app these three rows are like the base layers and I’m going to stack them like cake in a column so my final design is a column and within that column I have Row one two and Row three bringing together the final application design how cool all right let’s tie everything together the real question we need to know to get started is what do we need in order to set up our main window screen to get our app started here we are if you memorize any code in this first part of the lesson memorize this because we will use this every time we start creating an app at the top of my code you can see all of our Imports I’m importing QT from QT core next I am importing all the widgets I need to build the app for from QT widgets our two most important Q application Q widget everything else is optional based on what you are trying to build after our Imports according to the code Burger we have our app settings and our app main objects these main objects are app in main window one of them should always be called app this is a generic name that’s used across the world by other Developers app is equal to Q application Q application is our class remember the parentheses and it also takes an empty list as an argument next I like to use the name main window you do not need to use that the value of main window is Q widget that allows us to create this window app once we have our main window object you can go forth and you can start to style or give your app the settings if you want to give your app a title you can do that with the set window title method that’s linked to our main window if you want to give your app a starting size what size will the app be when it first opens you can resize with a width 300 and a height of 200 you can choose any width and height you would like soon we will be creating all the objects that we’ll be adding to our app but the last two lines in order to get our app template all ready to go is we need to show our main window and we need to execute our app great let’s put together our starting app and head over to vs code I’ll see you guys in our next video [Music] alrighty here we are in vs code before we jump into start coding let’s take the code burger and let’s put it in here to VSS code to give us a starting template what was number one again well number one was we want to import our modules okay then we have our main app objects and all of our settings great once we have our main app objects what should we do we should create all app objects so anything we want to see in this app finally we can have all of our events and then we want to show slash run our app these would be the things inside now we do want to design where do we want to design in our app well we want to design right here okay so all of our design can be done after we create the main object so I’ll just say all design all righty to kick things off let’s go up and let’s work through and get a basic template going for the foundation of our app so importing our modules we can say from PI qt5 that’s our framework now I can attach the module I want to go QT core import class so I want QT class from the QT core module from the framework pi qt5 all righty now we can get our GUI going we can get all of the widgets we want on the screen so let’s import those I like to start with the two most important ones which are Q application and Q widget so right here Q application Q widget what else do we want to see in the app well I know that I want text so we can say Q Lael I know I want some buttons so let’s say Q push button finally what type of design are we going to be doing well we’re going to try to do some rows inside of a column which we’re going to actually check out here in our next lesson so before we do that let’s just say QV box that gives us one initial layout now that we have everything imported let’s work on our two main objects so I’m going to say app equals our Q application class and remember that this takes an empty list as our argument next up to kick things off let’s make a main window and we can say here Q widget you can name this anything you want my names are going to be to help you further your understanding so this is my main window I’m going to call it my main window now the other final settings we can do is we could set a title for our app right and we could say random word maker okay and then we could set the initial size what size do we want the app to open with I could say a width of 300 a height of 200 great all righty to close things off for our start all we need to do is is we need to take our main window and we want to show the main window while the main window is showing we can execute or run our app let’s run our code and observe what happens there we are our starting template you can see that the initial size is 300200 but you can make it smaller and you can make it bigger okay and then you can also see the app title is random word maker which we gave it here now this is great because every app we make will start with this this is the foundation it’s like you’re pouring the concrete to build the home so we can now build on top of this now remember there are many ways to do a certain task don’t be afraid to try your way I’m breaking this down so we understand the key fundamentals to build apps with pqt let’s head over to our next video and in that lesson we are going to address the design of our app and how we can do that I’ll see you guys in the next [Music] lesson [Music] Welcome to our next video now that we have our starting template ready to go it’s time to design our app how can we achieve this look right we have our three rows and these rows are held in one master column so the layout tools will be using are going to be our QV box layout V for vertical and our qh box layout or H for horizontal these will be used to build our rows and the columns how will our code look well now that we have our app ready to go we need to create all of the objects or widgets that we want to store in this app on my screen you see one 1 2 3 4 five six seven objects therefore we should be creating seven different objects they each have their own name but the value can still be from the same class they’re different objects from the same class my title text well that’s just text remember in pi QT anytime we want text we can say Q label when my app first starts all of these should actually be a question mark right until we start clicking the button so I can create those here to end with I will create three push buttons each button is a different object but they all say click me now that we have created all these objects you’re going to use in your app it’s now time to design the app you won’t be able to see any of the objects if you were to run your code now it’s because we can’t see these objects until we add them to our layout and we set that to our main window as I go through this course remember there are many ways to solve a problem in coding I am showing you one way and I’m breaking that down to a way that you guys can easily understand if you find a different way or you want to try it yourself I encourage you to do so here you can see each of those correspond to an element on the app screen and that’s held in our final QV box column now that we created those objects I need to get them on my screen here I have made my master layout which I know at the end everything will be added to but I also know that I’m going to have one two three rows so I can create three row layout objects right here next up it’s time to add things to the row so I can start with Row one because I know it’s going to be at the top what do I want to do I want to say Row one I want to add the title text to it it’s going to do just that if I want I can give alignment to the text and I can say I want it to align in the center enter you can see I’m using the QT class from QT core that we imported now that I know Row one is done check I can move on to row two and I can do the same thing row two I want to add the widget text one which corresponds to that and I can also give that alignment row two is done we can add the buttons to row three this is adding all of the objects you just made into each row now if you’re running your app no what do we need to do now what’s the next step in the code Burger now that we have our rows we need to add them to our Master column I can take that and I can say master layout I want to add Row one it’s important to add these rows in the order that you want to see them remember python reads top to bottom we need to code like that too once we have everything in one place or should I say in one master layout I can take my main window and I can set the final layout to be my master layout if I break that down one step further here is what that would look like we’re creating our Master layout that everything eventually will be added to I can create three rows because that is how I’m choosing to design my project then we just need to go through and we add each row once we’ve added the widgets to it we add each row to that Master layout finally you can use set layout to set the final design of your app to your main window screen this ties together perfectly the code Burger you guessed it you probably didn’t guess it but it does bring in the code bger I’ve just gone through each step individually and how they align and how they work together you have a designed app now but let’s just touch on the final elements what is this app going to be doing well it’s going to be generating a random word and displaying that on the screen every time you click a button how could we do that pause the video take a minute just think how could you do that that you heard the word random you should have thought the random module I want to import the function Choice from random now Choice takes a list as an argument and it randomly chooses one of the elements from that list so I have a list called my words and I’ve just put these random words in here I then have a function and when this function is called I have a word variable and this Choice function is going to choose one of these random words so word equals one of these I can then take my text one object which we already made in your app and I can now set the text to be that random were that is how I can use the set text method with our app to set the text of an existing object on our screen the final question that we are going to address is event handling how do we connect a button how do we activate a button to work in our code what event could we possibly use in pqt in pqt to kick things off we are going to be focusing on one event now you can see that I have my object button and that is a q push button that object is created here I then have a function and every time this function is called it’s just going to print this button is working that’s all the function is doing I take my button objects and I say when the button is clicked we want to run the test function clicked that’s the event type in pqt let me translate this now the event would literally translate to when this button is clicked I want to connect to this function and that is how we handle events in pqt in our first app we are just going to be looking at the clicked event but in other projects that we do in this course we will be learning about other events as well all right let’s head over to vs code and let’s finish off our app I’ll see you guys in the next video [Music] here we are in our next video in the lesson we introduced how we can create a layout and design our app the way we want it to we also addressed how to get the objects to appear on our screen because we now know that after we create an object we then need to add it to our design let’s start off by creating all the app objects that we need first up I’m going to create a title cuz I know I’m going to have a title that is going to be text on the screen and according to my app I can just put random keywords because that’s what I want the title to be I will then have three different text so as long as they all have a different name because they’re all different objects that’s fine and they can still all use the same class initially when the app starts I want my text to be a question mark when we click a button this is going to change to a random word great we have our text objects what other objects do we want the buttons so for each button you should create a q push button it’s a q push button that can say click me we need to give them different names great we now have our seven objects all of these we want to see on our screen now that we’ve created these objects it’s now time to move into our design we got to get these onto our our layouts onto our screen the first thing we can do for our design is let’s create all the layouts we want now I know that my final layout my master layout I want everything to be held in a column so I’m going to make that within this master layout column I know I’m going to stack some rows it’s going to be like cake so I want to have Row one row two Row three in order to get that I need my Q hbox layout therefore let’s go up and let’s just add that on to our Imports let’s say qh boox layout now that we have that I can go forth and I can say okay I am going to make a row one let’s make a row two and Row three these are the designs in the app great we can start to add our objects how do we add these widgets to our screen well do you remember the method we learned add widget what is that going to be linked to well let’s say hey python in row one I would like to add my title to the screen I would like my title to have the alignment of the center of the screen so I can pop that in just like so that’s what that translates to row one I I would like to add my title my title is a widget Q Lael and then my row is the layout great that’s Row one I can move on to row two in row two we’re going to have more I’m going to have text one text one is going to have its alignment again and I can say once again align Center but row two is also going to have our other two texts so I can say text two text three remembering that python reads like a book left to right top to bottom so the order we add these to our rows it’s going to go left to right text one text two text three that concludes with the final of adding our buttons to the screen our buttons do not need alignment so I can just take it and we can just add the button how it is button two button three awesome look at our design okay if any of that is confusing go back through some of our slides rewatch the last two minutes of this video right we create our layouts and we simply just go in order all right I’ve made my layout I’ll just start with Row one we do what we need to do row two and Row three now that we have all these rows I just want to drop them into my master layout here is US using the add layout method now remember that we use the add layout method because a row in this example is not a widget it’s a layout if we want to add rows or columns together we need to use add layout so how we could translate this is Master layout we want to add Row one at the top Master layout I would like to add row two under Row one and then Master layout we can add Row three under row two now that everything is stacked in our Master layout let’s just say okay I have my final design ready to go main window I want to set the final layout to be my master layout incredible let’s give our code a run there we are you can see our app I have the title which we’ve given it right here I have my three question marks ready to go for my random words and then we have all the buttons we added now if you try the buttons we have not connected any events yet that’s what’s yet to come in the next video we will implement ment our random words as well as the events for each button I’ll see you guys in the next [Music] video Al righty welcome back let’s get this app finished now we need to introduce random words and Link our buttons with our Events first things first let’s create some random words so when you hear the word random you should immediately be thinking of the Python random module if you’re not familiar with this do a little reading on the documentation it’s one of the built-in python modules like random or time or math python has these modules and choice is going to allow us to choose a random word from a list speaking of lists let’s go down here with all of our objects and let’s make one let’s just say my words equals a list I’ve already prepared some words you guys be creative you know choose a hobby that you’re passionate about and use those words here all righty so let’s see let me Mark these we’ve imported choice we have a list of words we’re now ready to make some functions I’m going to add one additional comment add functions I like to create my functions down here in the bottom okay after our design after the design elements of our app there are many ways to do this again and if you think of a different way go with your way try your way the way I’m about to do it is to make it more readable for you and easier to understand in the big picture of things it doesn’t matter if you do the same problem in three lines of code or 15 lines of code were you able to solve the problem if the answer is yes awesome that’s great and you should be proud of that let’s make a function now to be exact I’m actually going to make three functions they’re all going to be the same thing but they’re going to be linked to different events so random word when I call this function I would like to get a random word from my list of words so I’m going to use the choice function here and I’m going to insert my list so now word is going to be one of the random words from my list it could be Hello Goodbye test app any of those I can then take my object text one remember we created three of these one 2 3 currently text one is a question mark I want to update that value or change that value who remembers what method do we use to change the value of an existing object set text so I can link set text method because I want to change the value of text one and what do I want the text to be whatever random word was chosen that’s what we want great I’m going to use this now a few times so let’s just take this what do we need to change well uh random word two we now want to change text two and then random three would like to change text three great we have our three functions one two and three to close things off we need our pqt events and remember we have just learned our first event of clicked clicked is linked to a button object so let’s say button one when button one is clicked I want to connect with my random word one function when my button to is clicked I want to connect with my random word to and I’m just going to take that for the last one and we can say button three and random word three great run your apps play with your apps experiment and review our code what did we just do save this code somewhere as it’s going to help you build our future projects it is the code Burger structure it’s what we’re going to be using in this course I’m going to give my app a run there we are click ah look at that all different that’s great we have it working exactly how we wanted it to very well done we have put together our first app but fear not cuz what we’ve learned here we are going to use in the remaining projects of this course I’ll see you guys in the next lesson where we are going to introduce our next [Music] project welcome back to our next project in this project you’re going to be putting your knowledge of QT widgets to the test as we build an interactive calculator with pqt before we dive into this project let’s take a look at the famous code Burger one more time remember the structure of what we’re trying to do here we will use this structure within this project as well remembering all of our Imports our main app objects with the setting once we have those two feel free to create all the widgets you want to see in your app once you have those we can then design the app with our layouts and set that to our main window when everything is set it’s time to run and execute your app this is the code Burger so in the past we have been using QV box layout in qh box layout and remember that V is for vertical or a column and H is for horizontal and row you got some practice with these in the last project looking at this calculator app how would you design this do you see rows and columns does that make sense right what other options do we have well what I see is a grid what if there was a way to create a grid for us there is with pi QT we have a layout called Q grid layout and you can see that I have my object grid and the value is Q grid layout which I’m going to use instead of creating four columns and five rows that seems really repetitive I can create one grid and add things to my grid which becomes incredibly useful for us but how do we add things to this grid do we still use add widget yes we are adding an object to a layout we still will use add widget but now add widget actually takes two additional arguments we create our grid object then we say grid we want to add a button where we need to specify the row in the column right so if we translate this layout add this object to this Row in this column now for this to work right we do need to create some type of index or current position in this example I’ve said row equals 2 in column equals 1 that would actually give us the number five button if you’re thinking how that doesn’t make sense remember programming languages start on zero so I’m actually saying row 0 1 2 column 01 that gives us number five we are trying to take our knowledge from an idea all the way to a completed application currently we’re on the number one you know how to get to number two and after the last two slides you should have a rough idea on how we can achieve number three you do see a new object in our calculator this little guy is called a q line edit tool and this is where we will see all of our Expressions being entered and evaluated number four is like a final bonus redesign and it’s a way for us to add slightly more details to our app we can change the font change the color things like that that’s our goal for this app to go from design one all the way to design three if we can get here this is a completed product we can then worry about getting to number four looking at this calculator now this whole grid system it seems like it’s going to take a while because I I have I think at least 17 buttons maybe 18 buttons so it seems really repetitive how can we deal with repetitiveness in coding what do we have for this Loops what are the two types of Loops you know in Python the while loop and the for Loop the four Loop is used to iterate to go through something else let me propose that we actually Loop through to create our grid so let me break that down to plain English in general tasks before you see any code I’m making a for Loop and I’m going to go through this list this list will be all the string elements that I want my buttons to say what do I want to see on my buttons like the letter c the less than sign the number four all of those I could add to a list and I could Loop through and say for every button text in my list every time I Loop through one I want to create a new push button object with the current text I’m on two for that object object I will create an event only for that button great then I want to add this new button to my grid layout one two and three all work for one button number four before I make the next button I should change my row and or change my column so think about this how can you achieve this and how can you achieve this with using a for loop as well as counter variables if you’re up for a little challenge pause the video here give it a try and then come back to continue watching putting this into code on the outside of my for loop I have two counter variables responsible for keeping track of my row and column I’m going through my list of buttons and every time I’m creating a new button object a new event for that button and then I am adding I’m taking my button and we’re adding it to our button grid every button is being added at an index a position row column once we add one button I want to increase my column or change my column if I get to four columns then I want to reset my columns and I want to go down to the next row this remember we start on zero so it’s actually 0 1 2 3 increase row 0 1 2 3 and I’m repeating myself amazing very well done I would love it if you took the knowledge that we just learned in this lesson and you go on and you create your design and create the initial product for our app I’ll see you guys over in vs code where we’re going to put all of our knowledge to the [Music] test Welcome to our next video in this video we are going to put together our initial design here in vs code for our calculator app let’s get started so who remembers the code burger right let’s go through those steps what will we need in order to complete this project well we really just need some widgets okay so I’m going to say from pqt 5. QT widgets let’s import the two most important ones so Q application Q widget what else will we need to create this well we need our new tool our q line edit we will be using push buttons then our layouts we have our qh which we can use for row if we need it we have our QV box for columns and our new tool is our Q grid layout which I can import up top like so um looking good all righty now that we have those we can create our starting template so our app which is our Q application then we can say our main window amazing who remembers how to give the main window AR title let’s say main window. set window Title Here I can put calculator app then we can take our main window and we can resize so the initial resize let’s say the width can be 250 and the height can be 300 we can see how that plays out when we’ve run our app let’s put in the final two lines what do we need to show our starting template well heading down here our final two lines we can show our main window and we can execute our app great let’s give it a run all righty there we are our starting template what do we need on here we need to now design the layout using our Q grid box our q line edit and then our push buttons that we want for our clear and delete as a as a starting template so this is what we’re aiming for all right and I’ll bring this back up as we work through this project but this is the goal up top in a column we have a q line edit this is like where I enter something then we have our Q grid layout with all of our buttons and the last one could be a row here that I may put and that contains our final two Q push buttons so to get our row and our design well let’s create all of our objects first so even before my design let’s go back and let’s say something like uh all objects or widgets right CU that’s what they are what do we need here well I need a place for my input so let’s say like a text box cuz that’s that’s what it can be this is our q line edit now q line edit does not take anything I will make my grid which is a layout so Q grid layout now the way we looked at this in the lesson is we have a for Loop that can go through a list and every element in that list or every position it can append or put that into our grid layout so I need a list of buttons now what order do they need to go in and we need to think about that let me bring up our example of the app again I’m going to Loop through so either we want to do it in columns 7410 or I could do 789 SL 456 star let’s go with the rows so how about we start by making this I could I could probably keep this up as a template uh so let’s say 7 8 n slash right and then I’m coming down the row we have four five six let me enter the rest of these here there is our list of button text now this makes it really difficult to see so let me re Factor this and I’m just going to make it look more pretty so that it’s how it would appear on the calculator right so there’s the same list I’ve just put it in rows now and this is essentially what we want to see on our app screen right when the app fires up it appears and you can see how each row of this list is corresponding to the row in our calculator now I just made this look like the calculator will but one long list is the same this is easier to understand and interpret now the final two buttons we can make outside of our list and those can be our push buttons let me close the app let’s create a clear button and this will delete everything in the Box I’ll put C and then we’ll say delete and delete could be a push button like we could do that for delete we could also write clear and delete might be fine clear let’s keep the symbol for delete uh all righty so we have everything that we want to see on our screen at this point let’s go through and let’s map this out and get our design we have our objects we need our design to start flowing how could we get our design started here well let’s create our layouts so I’m going to say master layout I know in the end everything will be held in a column that makes sense at the top of my column I would like my text box right that input so I’m going to put that right there directly under this I would like to actually add my grid of buttons which I don’t I don’t quite have those yet so I’m thinking out loud here then at the bottom we want to have I actually want to have a row so let’s also say add layout and let’s say button row while I’m here let’s create that button row so I’ll say button row and within that button row I would like to add my widgets so from left to right let’s say the Clear button and then we have the delete button let’s focus on our grit we have everything going and so we can see that let me turn off the grid let’s set the master layout to the main window cuz that’s our final design I’m going to run my program this is what it looks like currently we have that box at the top we want we have clear and delete I want to get the buttons between those two now so here is where I’m about to implement that Loop and remember every time we Loop over we are creating a new object with a new event why while also increasing the row and the column as well I’m going to shut the app down trash the terminal we are going to go right here before our design this looks like a good place before our Design This is where our for Loop is going to take form now I’m going to create my two counters so row and column and this will keep track of how many buttons are in each row as well as each column I can say for every text in this list so I have my list of buttons and I want to say for every string for every text in here so let’s say for every text in my list of buttons I want to create an object for the current button I’m on so I’ll say button equals Q push button uh what do we want it to say well I want it to say whatever the current text is in the loop when this Loop first takes off text is going to be the number seven number seven will be the text value of the first push button we create for this button it has the object name button I can create my event and I’m going to say I want to connect it to some type of function which actually I don’t have yet okay so let’s keep that empty while we have our button created we have the event created which I could say none while it’s also none let’s turn it off we can now add this to our grid let’s take our grid let’s add the widget what widget do you want to add I want to add the current button at the current row at the current column looking great all righty before we go on any further I now need to increase the column I want to move to the next button on the right so column plus equal 1 if my column is greater than three I want to reset my column so column now equals zero and I can increase my row because it’s time for a new row this puts together exactly what we want to see in our calculator app the final step is let’s just turn this back on again we can add our grid to our Master layout design when we give the app a run we should see our basic template with all of our buttons looking great this is the basic form of the app now notice it doesn’t do anything yet but we have everything ready to go for adding our functionality I’ll see you guys in the next lesson where we are going to discuss how we can add functional ity to our [Music] app great now we have our design for our calculator app completed but what’s the problem it doesn’t do anything yet that’s fine because adding the functionality to our applications comes after we create our initial design so in this lesson we are going to learn how to create that functionality as well as learning how to evaluate our expressions for example 2 + 2 evaluate to 4 in order to do this we could do this a few ways now what are you thinking about right now in this moment how would you add functionality to our app you may be thinking a few things and that’s okay before watching this lesson you may want to try and Implement your own ideas in logic which I highly encourage you try I’m going to show you one of the many ways to solve this and the way I’m going to show you is actually done through one sole thing function I am creating one function called [Music] buttonclick this is the only function that’s actually required to run our app you could make a function for each button sure that’s just a lot of code but would that work absolutely it would work what we’re doing is going down we are checking if the text of the button is the equal sign if it is then we set the value of this variable to be the equal sign if I press the button that has the letter c on it I would like to clear my q line edit object if we press the less than button we would like to cut the last element off our current text do you know how to solve any of these currently well let’s take a look at some of them our first one let’s begin with this so when we click a button I want to get the text value off of that button object do you remember how we can do this well we can use the text method and this method is linked to an object and it gets the text value of that object which is pretty cool you can see here here that I’m getting the text value of the button I’m getting the text value of the input box the q line edit box and I’m doing that here here and here pretty cool all right now that we’ve collected the text from the button we need to evaluate the expression that we enter into the input field for example if you clicked 3 + 5 we need to now evaluate that we want to change that to 15 any thoughts on how we can do this in Python well in fact you may have seen this python function around before python has a function called eval this function is made to evaluate expressions so if the expression is true if the expression is allowed it’s going to run next if we press C we want to clear the input field how can we do that well thanks to Pi QT Pi QT has a method called clear we can link clear to any object that we want to Simply put clear great this brings us to our final one if we press the delete button we want to delete the last item that we entered any thoughts on how we can cut an element from a string you should know this from working with strings and string manipulation as well as working with lists in order to cut I have a variable called current text and that is the text value of whatever is in my input field so I’m going to take that text and I’m going to cut using our square brackets to index the last position of the string minus one this is a key fundamental of string manipulation that you should already feel relatively comfortable with this takes us to our last method now a current problem we actually have is all the buttons have the same event or the same Target of event and we need a way to tell them apart but don’t worry because Pi QT has actually got us covered for this as well we only need to do this if we are making one function for our entire application which in this lesson that’s what I’m doing we can use the sender method and I’m going to link sender with our app object the sender method was created specifically to tell the difference between multiple events in Pi QT so that’s the first thing we do I create a variable called button and I am tracking which button did I click which button sent the event to me amazing the last thing we can do here is I’m going to throw in a try statement because I could potentially get an error I would like to try to evaluate the expression if that’s not possible then I just want to set the text of the input to error why is this useful why would this happen well if you pull out your iPhone right now any phone you have and you pick any number and you say I don’t know 20 divided 5 you’re going to get four but if you say 20 / 0 you’re going to get error that is what could happen what if a user tries to divide by zero we want to anticipate what could the user do wrong and I’m going to catch that right here so as a final precaution I am going to add my try and accept statement to catch any potential errors amazing before heading back into vs code to implement our app functionality you are going to see the next few videos in the next video we will finalize our app then I have prepared two remaster challenges for you that we should be getting comfortable with here are your two challenges for this project once you have a working product your first challenge is to remaster your app into a class based application so I want you to try to build your own class and refactor all your code to get it in your own class all right if you’re able to do that why don’t you try to add some designs and styles to your app as a hint you can check out the Q font module from pqt this will allow you to play with your fonts and for all the styling check out the method set style sheet if you have ever worked with CSS you’re going to be ahead of the game because we can add CSS to our apps I’ll see you guys over in VSS code where we are about to finish our calculator [Music] app amazing now we’ve addressed the functionality that we will be adding to our application here is where we left off I’ve cleaned some things up a little bit as we’re getting ready to add in our function the question becomes where should this go so if I take away all of our spacing here based on our last app we put the function at the end but I am going to get an issue because right here we need to connect to some button in order to create this event so it has to go before our Point here because this needs to go before our layout our function can rest just up here right after we create all the elements we’ll use all those widgets I’m going to create my function and this function is going to be responsible for Anytime a button is clicked so remember we have all those buttons on the screen and each button really has the same function call so we need to check what is the face value of that button what text is currently on the button what we can do is I can create a variable and I’m going to listen to who sent the message who was clicked that’s what it’s listening for then I can take that button of who was clicked and I can take the text value of it right so those those two are working together right there first I’m listening to what button was clicked then based on that button I’m getting the text value from it we can then check if that text value is actually the equal sign if it is then we want to get the text that is within our object text box let’s get that we can then try to evaluate so remember that this is an expression and I’m going to have a result in this result we want to evaluate the equation so like 2 + 2 my result should equal four I can set my text box as the updated value of whatever my result was making sure that I convert that to a string what is every Tri statement need well every try statement we want to have an accept we want to catch that so how can I catch that for every exception I don’t just want to say accept I want to say exceptions overall and I can give them a nickname and I’m just going to refer to them as e e means every
exception so I can just print off and I’m just going to say error let’s put two dots and I’m going to say e so that I can get that type of error as well if we press the equal sign we evaluate that expression let’s check if the original button text is actually clear right does the text value say clear if it does we can take our text box and we just want to clear the value that’s within it that’s where the pqt handy clear method comes in what is the last button that needs its own as well well our delete button right if we press delete we would like to be able to backspace so if the face value of our button is that sign that we set we can then try and do a few things we would like to get the current text within our text box whatever it is it could be 85 minus 2 I want to get 85 – 2 I want that value it could be 100 I want to get 100 from there so let’s say let’s just say current value it’s the current value within that box and that is equal to my text box the text within looking good in order to update this now every time I click I want to update the text box so I can say set text because I want to change the current value of that and I want it to be the current value but I want to take off the last position so I can do that by signaling this as the index great and to touch up I want one more but it’s going to trigger no matter what so if I put an else here now that we understand that each of these are a condition we also need to understand that I can only press one button at one time all of these are a part of one condition instead of saying if let’s say also if or El if our final else we can say the current value is going to be the textbox value and let’s just say our textbox set text our current Value Plus text now remember text is going to be a button value so if it’s not an equal sign if it’s not the clear button if it’s not the delete button then it’s going to be a number or an addition symbol a subtraction symbol we want those to appear in the text box that is what this else is doing this is adding numbers to the text box as we click them this is our overall function and the functionality to it we just need to connect our buttons to this function and we have a working app going down now let’s take away all this space we can turn back on this event and I’m going to put in here the name of our function which is button click at the bottom here right before we execute our app let’s take the clear button that we made let’s say when that’s clicked I want to connect also to button click and when the delete button is clicked that can also connect to our function button clicked looking great amazing all within 80 lines of code just about we have a working calculator app well let’s check that it’s working that was our final stage of the basic form of this app all right let’s go down here let’s say 55 * 62 equals wow there we go looking good minus 36 equals great clear that works choose we can delete amazing well done coming from the first warm-up app that we created you were introduced to these basic concepts of design and how we set up a template app in pqt this is your first real world application in your first project this calculator app very nicely done what we’ve learned here we’re going to continue to build on in the next video we are going to learn how to refactor this code as a class-based application I’ll see you you guys in the next [Music] lesson as we enter this lesson let’s address who we did in the last lesson we completed the basic functionality of our calculator app a fully working app in Python with pqt using this framework now in this video we are going to learn how to refactor our code into a class-based application why is this so important well pqt is already structured in classes as you can see here with QT widgets it’s everything we already have so you should feel confident and comfortable creating your own classes methods and properties the second point is as we go forward in our projects they are going to become more class based focused as this course is designed to take your basic programming skills of python in object orientated programming and grow on that idea that concept of o or objectoriented programming as I’ve introduced how this framework is class-based it’s now time to start making our projects in a class right here is where we left off in our last video our app still functions I haven’t added any more code it’s now time to refactor we looked at this very briefly in the introduction lessons of this course but if there’s anything that you’re hesitant about feel free to check out my other objectoriented programming course or just go back a few slides and review what we looked at in order to do this let’s create some space here so pretty much everything I want to have in a class and the last two things I’m actually going to remove our app and Main window because those will automatically run here at the end so I’m just going to store them down here for now going up to our top let’s try and keep everything so I’m going to create a class and I can call this Cal app it’s my calculator app everything below we pretty much want inside of this class all righty I am now storing all of our original code in a place called class app now we still need a main window and as you saw I just removed my main window so how can I pass in a main window that my class can use well the obvious one that we may be thinking is Josh why did you just remove that well what I can do is I don’t actually want to do this I can take first off let’s uppercase that I can take Q widget and I’m actually going to inherit Q widget why can I do this well remember in pi QT all of these are classes so a class can inherit a class I’m using this Q widget as a super class I can now take that away I’m inheriting that I’m left with all of our starting code and this code starts as soon as the app starts so what is that special Constructor method that automatically runs when an object is called in it we need our initializer function so let’s say in it I’m going to put self I’m going to activate my super class so with our super function we can initialize the super class now that we have that let’s take all of this we’re just going to put that right there inside main window is nothing but now that I’m working with a class these are not variables they are now properties self is referring to the Q widget remember that originally I had said main window equals Q widget I’m inheriting Q widget so instead of saying main window it’s kind of like saying self my S is a q widget I am a q widget so I can say self. set window title instead all righty all the widgets we originally made I’m just going to come down here and let’s turn those into properties so self self and self looking good all righty uh let’s continue down you can see that I’m given an error Here in My Method this has become a method it’s now a function a class everywhere it says text box I don’t have textbox anymore that has become a property correct so let’s just add our key keyword self just like so and then pass in self as a parameter looking great missed one self going down this where we create our buttons that should be done at the start right that’s done through the initialization process so I can refactor that by putting that just directly inside our Constructor in it there we go looking good I’m going to give self here so self button click my grid has become a property self grid and our button list is now self buttons already going down our design once again when the app fires up in order to start the app everything should be done at the beginning so all of our design now that we’re working with classes I can remove this and I can put this inside in it once again I’m going to drop down here and let’s just drop it right there all of these we can tab over remember that anywhere we have main window we don’t have that it’s now self uh all of these guys have become properties going away from the variable form so let’s add self looking great all right so our class has been restructured and refactored let me clean that up so now in it initialize start when the app starts everything is done all the design is done right because that should be happening we then have our method Now button click that’s only triggered when we click the buttons and the reason that I can put my design before now is because this is a class the word self unlocks everything in our class that we can use anywhere we want we can go to our Bottom now for this to work if we ran it well let’s run it and let’s watch what happens it’ll make for a better explanation I get this massive window blank screen that doesn’t look right okay let’s close out what we need is we can use the python condition that we like to say so if the name if you’re running the main file is what this translates too if that’s the case then I want my app to run or execute I want to create an object I want to show that object now I am using Q widget remember we don’t need Q widget anymore because we gave this as the super class to our calculator app so this really should be Cal app main window is fine I can use that outside here running our app it’s now brought back to life 78 – 35 equals there we are a refactored form of that app through classes heading over to our last video now if you’re up for the additional bonus challenge we will be learning a new class that I gave you the hint of using Q font as well as the method of set style sheet to design your app a little bit more I’ll see you guys in the next video [Music] all right let’s add some design fonts and color to our application in order to change the font of our line edit and other tools let’s import Q font so I can say from PI qt5 this is from the qtgui module I can import Q font and Q font I want to use that to set the font of the text box so I can use the method set font and inside here you can see it actually says Q font so let’s say let’s put our Q font class in there as the argument to our method set font and I can actually put the type of font I want so let’s say uh helvetica as my font and then I’m going to style it as let’s say a size of 32 all righty so that’s step one we’ve styled that let’s go down a little bit and style the buttons so here we create a button here we create a button button event before we add it to our layout let’s style it so let’s use the method set style sheet so this is going to allow us to essentially use like CSS in pqt which is quite cool and wherever you are in your programming Journey you have probably come across CSS and HTML before if not this will be a great time to just briefly read through some of the CSS guidelines So within this method set style sheet I’m going to specify a few things and I’m going to specify all this as a string this is going to be just like normal CSS So within any CSS file we would typically put the name of the element that we want to affect so I want to affect a q push button that would be followed by a set of brackets or curly braces the first thing that I want to affect is I’m going to say font and I want to give it a font and I’m going to say this font is going to have be 25 pixels or a font size of 25 and let’s be creative here and let’s say comic Sands as our font style and then I would like to give a padding as well of let’s say 10 pixels to each button so I can specify that like that great so each button is going to have this styling to it all right we haven’t added the color we’ve given it a font size a font family as well as padding going down to each button now let’s take our Master layout and let’s set our margins so this is going to be a small amount of spacing in between all of our buttons and let’s say I want there to be 25 the right left top and bottom that’s the margins that I’m giving each button and I can justify it just like that finally to end things off let’s go down to to our bottom right here I create my main window object before I show my main window let’s set some styling to this now the question becomes what do we want to style I want to style my entire app and our entire main window is our Q widget so I can set that like so in here let’s just say uh background color and let’s give it background color so let’s say like uh o I don’t know these let’s say 1 two three interesting color it’s like going to be a really darkish black blue let’s try it let’s run our code okay so unknown background color and that’s because I spelled background wrong you can see the comic SS taking place that’s really cool let’s go down uh background and I also noticed one more thing that we didn’t put in O okay so far too dark right I’m not I’m not a fan of that I’m going to change a few details let’s give it like a lighter color and I actually have a color right here and also my delete button and my clear button they did not have any styling to them I’m going to go up so I actually create them right here I have my self. CLE property and myself. delete and both of these are going to be our buttons for each each button let’s say self. CLE let’s say set style sheet I’m going to actually take this because I want the same properties as my other styling great we can copy this and for our last one let’s just set our delete button running our application there we are it looks amazing it looks much better than the last product we had congrat congratulation that is the completed calculator application for our course going into the next project let’s take what we’ve built here and build on top of that and create an app that’s going to add even more functionality that we can use in real world situations I will see you guys in the next lesson for our second project [Music] Welcome to our next project in this project you’re going to learn how to combine multiple modules to build an interactive photo editing app in Python with pqt and the pill module let’s dive in and let’s take a look at what this app is going to look like and what it’s going to be able to do Here’s the final product of what we want to get our app to look like what can this app do well we can select an image from a folder from the desktop we can apply filters to the image before we edit it we can edit all of our photos using the tools that we Implement and finally we want to be able to save the photo we edit to our desktop pretty cool now looking at the app what widgets do you see in this app what widgets do you think we’re going to import from pqt to build out our design here we go how many of these were you able to get right hopefully all of them if you happen to miss any it would most likely be the Q combo box and the Q list widget as we haven’t used these widgets yet our Q list widget allows us to have a list of things within our app and then the Q combo box is essentially a drop- down box and this box drops down and it allows you to select an item from that box all the other ones you’re familiar with and you may be thinking Josh this is a picture why did you say Q Lael well we’re going to look at that closely but in the initial design of the app it’s easiest if we just set this area to something that’s not the picture yet so I’m going to say Q Lael in the future we are going to change the value of this Q label to become a picture the final a point we need to think about now how would you like to design this app what’s going through your head right now well so far you’ve learned three layouts we have our QV box which is for vertical or columns we have our qh box horizontal row and then from the last project you were actually introduced to Q grid layout what do you see how would you design our app how I’ve put it together is I have a master row this master row everything will be added to but instead of adding it individually we can create one two columns we can add the items we need to these columns then we can append it or add it to our row pretty cool now before we get into this new module pill which is going to help us edit photos with python and before we Implement any functionality to our app we need to focus on the design of our app so far we have created two projects you were introduced to pqt with our warm-up random keyword app in the last project you created your own interactive calculator I want you to use use the two projects and everything you’ve learned in these last two to create our initial design for our app here let me go back here’s a refresh of what you need to add let’s head over to the next video but before you do I want you to at least spend the next 20 minutes and I want you to try to design what you see here in VSS code I’ll see you guys in the next video [Music] here we are in vs code in this lesson we are going to set up our initial project for our image editor app let’s jump in and let’s set up our initial design starting things off what do we need to import here well let’s start with our design so from PI qt5 what widgets do we want to import well our two most important we have are our Q application let’s say Q widget what else do we need for this app well based off what we discussed in our lesson we’ll need a label we will put in some Q push buttons we have a Q list widget this will allow us to add the items we select to a list we have something called a q combo box let’s start to think about our design for the design we know we’re going to have some rows and we’re going to have some columns great I think that’s a good starting point for our wiek widgets for our alignment tools who remembers the module for alignment we can say QT core specifically I would like QT and we can start with that for our setup great I’m going to begin by creating the two objects that we need to start things off here so app and let’s say main window that’s our widget great I would like to set my app title so set window title and let’s call this a photo QT my version of uh Photoshop let’s set our initial size and I can say 900 and 700 great I’m going to jump down and let’s get our template shown so main window Show app dox execute I’m going to give it a quick run to make sure everything checks out before we jump into our design there we go great so it is working this is the size of our app and my template is all ready to go we are ready for the next part of our code Burger speaking of the code Burger let’s label a few things out to prepare us all right now that I have things labeled I’m going to jump here and I’m going to create all the widgets we want to see in the app now this can be in any order you want as long as we have them all So based on the app we’re trying to create I’m going to work left to right at the top we have let’s keep it with good name so I have a button for my folder and this will allow me to click and access my desktop so that button will say folder under that we have our let’s call it our file list and this is is our qless widget that’s going to contain all the files within the folder that we select we are going to have all of our editing buttons so now comes the question of what editing tools would you like to add in your project you can read some of the documentation and be creative to what you would like to add I have selected the following so I’m going to create a rotate left button a rotate right button let’s have a mirror let’s have a sharpness let’s say gray is easier than black and white we have a saturation and we have a contrast I could say blur as well that gives our tools more ability for each of these there each going to be a q push button and each of those will have a string so let’s just go down and let’s add those great we have our objects ready to go what would you like your buttons to say so let’s initially say left WR uh we can keep all these variable names that we initially used we can just keep those that brings us to our next widget that we need to add I need a drop- down box essentially so I’m going to call this let’s say drop- down box and in order to get this into Pi QT when you’re working with this widget this is our combo box so let’s call this a filter box and I can say Q combo box now we need to add the items what do you want to see in the drop- down box ideally I want to see all of these in the Box to do that we can take our newly created object filter box and let’s use the method add item I want to add a sing single item to my drop- down box the first one will be my original so I need that because when I apply a filter I would like to have the ability to revert or go back to my original photo so let’s say original I am just going to go down through each button I created and I’m going to add that in here as well I now have my combo box with each of my buttons added in there which we will use to apply a filter with later very good my final item is I want to create an object for my picture and this is the actual area in the app that our picture is going to appear but initially we don’t have a photo so I just want to create an object that I can set as the initial placement in my app later changing to insert a photo initially let’s just say Q label and the label is going to say image will appear here we can just put that text like so awesome all of our objects have been created which leads us down to our app design the master layout for my app so I’m going to create a master layout and I want it to be a row so I will set it as a cube hbox layout within my master layout I know that I’m going to have two columns so I can create column one and column two let’s begin with our first column so what do we want to see in this column starting at the top I want to see the folder button and let me show you guys our app so this is what we’re aiming for in our design I want to see this button up top above my Q list widget my drop down box than all my buttons let’s add those to our column one the first thing we want is the button for folder next up we would like our file list this is the Q list widget I would like to see our filter box and directly under that I’m just going to go through and I’m going to add add each button that we’ve created up here to our screen all of our buttons are here and they’re added so column one is completed and column one contains most of our objects the only thing that we want to see in column 2 is currently it’s just going to be our Q label or the picture box because I want to give my picture as much space as we can so we have more editing space column one and column 2 is completed what is the next step of our code Burger well let’s take our Master layout which is a row and we can use add layout to add column 1 as well as column two to our Master row or the master layout the final piece of the puzzle let’s take our main window and let’s set the final layout to become our Master layout let’s give our app a run here’s the app when it’s loaded now it looks a bit strange and that’s because this left column is actually taking up the most room that only leaves a little bit for our image when in reality we want to flip this we want to have this the opposite way I want the First Column to take up the least amount of room possible and give our image the most space we can let’s close our app I’m going to kill my terminal in here I’m going to justify how wide do I want column 1 to be out of 100% let’s say column 1 is going to be 20% of the entire screen this argument is called stretch it allows us to justify how much of the screen we want that column to stretch when we run our app again we now have it exactly how we want it to all of our buttons are on the left our editing tools and our drop- down box has the options that we’ve added to it when we click one we will have this apply a special filter to our image to see if we like it before we go and we click the black and white button great our design is done and we’re ready to add the functionality to our app I’ll see you guys in our next lesson where we are going to discuss just how to do so [Music] now that we have our app all set up and ready to go it’s now time to introduce to you this new module that we are going to be working with this new module is is called the pill module or more specifically the python image library now before we Implement any of this code within our project I want to take some time to just play with the pill library in its own file we can break that down understand that then we can take what we learned and use that within our app let’s take a look at how this new module is broken down the python image Library allows us to work with real photos in Python so imagine the photos you take on your phone or your camera we can take those photos and we can edit them in Python and if you broke this down this is like a really basic version of Photoshop but the more we build on the more advanced we can make our apps and if you notice here I’ve actually put this how I structured the breakdown of the pqt framework and the pill library is actually quite similar pill is like a massive library or module and within pill we have other modules that we can import individually to achieve a certain task each of these modules contain functions and properties of their own this is very similar to how Pi QT is working we will be using three modules from the pill Library the first one is called image and this is a class that holds properties and methods specifically for working with pictures as files so you should start to think now okay how do we work with files in Python how do I I load a textt file or a Json file in Python think about that and get a head start the next class that we can look at is image filter and this is a group of constant variables that we can use to apply filters or rotate our images apply filters or rotate our images remember that and the last one is called image enhance we can use IM image enhance to enhance our images so if you’re used to photoshop or the editing tools on let’s say Instagram there are tools for saturation contrast and Vibrance we can use these with python and we can get those from the image enhance module now that we understand these three modules that we will use from the pill Library let’s take a look at a few code examples in what they they actually do behind the scenes here is some of the code that we’re going to be using and it’s not in any particular order except the first one and the last one because this is the overall structure we will use in the app going forward to kick things off we can import pill but remember pill is massive and just like Pi QT we don’t want to say import Star there’s too much happening so be more specific what do you want to import and what will you be using in your app I can say from the pillow Library import the image module class image filter and image enhance and this is the structure to import the classes we are going to be using in this app we have a method called convert convert takes an argument of an L don’t ask me why that’s what it is and what could convert does is it converts this image pick to a black and white image pretty handy pretty short and that can be done very quickly next up we could increase the sharpness of your picture now by changing the sharpness this is actually a filter we are applying to the original photo pick what do we want to filter well I want to apply the sharpen filter that is a part of my image filter module and it’s stored in a variable called sharp all right now we’ve seen the basic image module we’ve seen the image filter module now let’s look at the image enhance module if I want to make my picture more saturated or add color I can do so and how we do this is we create our variable and the value is we take our class image enhance and we apply a subclass color what do we want to add color to this pick this original picture and I can enhance that by 1.2 I say 1.2 because the picture begins at one so I’m increasing it by more or less 20% 1.2 if you want to mirror an image you can use your image class and you can use something called flip left right and finally to save a picture you can just use the pill save method we can link that to our new picture name and then our picture is actually saved within our desktop or within vs code now I asked earlier how do we open text files in Python and I wanted to get you to think about that because we can do the same thing with an image in Python we can use the python open function take a look at our code try and interpret what’s happening if you need to pause the video please do at the top we always import everything we are going to be needing in our code so because I’m using pill and images I’m going to import the pillow library then we can use the open function just like we do with text files with open the only difference we need to do is I need to specify what am I opening so with open I want to open a picture called selfie. JPEG and this picture I load I’m going to give it a nickname and reference it as pick so now anywhere I use this variable pick the value of pick is actually the picture we decide to open so I can show my picture I can then take my picture and I can enhance it I can add SE saturation to my pick it’s being passed down if we want to convert our pick to black and white the same thing I can take my new picture variable because I created that and I can convert that to black and white remember after we do something if you want to see it you need to show the new picture if you want to save it you need to save the new new picture but in this code did we save the pictures no we didn’t do you remember how we save a picture we need to use the save method I am saving this new picture black and white and I’m giving this new picture the name gray pick jpeg let’s head over to vs code in a new file outside side of our pqt app and let’s spend the next 10 minutes and let’s experiment with how this new library works and how we can use it to edit photos you are going to need a few photos you can use your own or you can head on to Google and find a few stock photos that we can use I’ll see you guys in our next video [Music] let’s take a step away from pqt you have just been introduced to a new module and this module is called the python image Library we use this to work with images in Python which allows us to open them and edit them so in this lesson we want to practice and introduce the steps we need to take in order to edit an image everything we learn in this lesson you will be implementing and using within your pqt image editor app all right let’s jump in and let’s import what we need so I’m going to say from the pillow Library I want to import image we need image to be able to open the image or do the basic edits to the image we are also going to be looking at a class called image filter this allows us to apply filters to the image as well as image enhance image enhance allows us to add contrast or saturation to a picture now that we have that I’m going to come down here and we want to open a picture so here I have the picture I’m trying to open I can delete this one right this is the figma logo I want to use this and I want to edit this in our main file I can put inside open my picture name whatever picture you want to use just drag it into VSS code so I want to open this picture and I want to give it a nickname and reference it as picture so every time I use this variable I just make picture it’s referring to the picture we’ve loaded in here but I can’t just open an image in Python I’m going to get an error open is meant for text files and Json files but because we’re working with the pill Library I need to say hey it’s actually image that I want to open and this image that I open I’m going to call it picture now that we’ve done that let’s just run a a quick test I can say picture. show and there we have it so it’s loaded up on our screen great I’m going to turn off picture Showdown let’s start with our editing techniques so a nice one to be introduced with is black and white let’s say that we want to convert our picture to black and white so I make a variable and the value of this variable is our original picture and I’m going to take that and I want to convert the original picture to black and white now that I’ve done that I can take this new image and I can save this image what name do I want to give this well I could just say gray.png save it when I run this I’m not showing the picture anymore I’m just saving the picture so it’s going to edit the photo and it should appear here great our code’s ran and it has appeared here I click that there we go our picture has been edited we’ve converted it to black and white it looks great let’s play with a few more going down what is another one we could look at well let’s say we want to rotate or mirror our image we looked at these during the lesson I won’t be doing all of them in this video so I encourage you to use what we just learned from the lesson and try the ones that I don’t talk about about here in our video Let’s make one for Mirror I’m going to say all right what do I want to mirror well I want to mirror my picture all right what do I want to do with this picture I want to transform it or transpose the picture great what do I want to do to it now that I can transpose it well I can take my image and I can say I want to do flip left right that’s going to mirror our image I can take this newly created image and I can save this image let’s just call it mirror.png running our code there we are with mirror and you can see the figma logo is actually flipped right if I go to the original it looks like an F for figma I go to mirror it’s a backwards F that’s awesome we just transposed and flipped our image with mirror we’re going to take a look at two more I want to use use one from each of the classes we’ve imported so I’ve used image and you can see how we use that with our open function as well as any type of rotation so if you want to mirror or you want to flip the image left flip right upside down we use the image class let’s say we want to apply a filter so a filter could be like blur or sharpen things like that let’s say we want to make the image blurry so I’m going to create a new variable called blur I’m going to take my picture and I’m going to apply a filter to that picture what filter do I want well I want blur and that it comes from the image filter class so I can say blur just like that we then take it we can save it give it a name of blur and we can run it now it’s quite tough it is blurred it’s just quite tough to see because this is an SVG image there we go that’s blurry all right looks great I’m going to do two more now and both of the next ones are actually going to be from the image enhanced class we’re going to talk about two ways we can do this I would like to begin with the contrast so I would like to add contrast to my image this is equal to our image enhance contrast what do you want to add contrast to my picture okay so I am telling python that I have a picture called picture and this is what I’m going to add contrast to it’s now called contrast I’m going to take that variable contrast and I’m going to say it’s now equal to the original contrast but I want to enhance it you photos start on one every photo is one a good starting point once we get into coding our app will be like 20% so 1.2 would be 20% contrast for this I’m going to go all out I’m going to say 2.5 that’s a lot so I’m adding a lot of contrast I can then take this new image let’s save this new image let’s run our code look at that that is a lot lot of contrast added to our image and it actually looks pretty cool we’ve turned all of our colors if I go to our original we came from that we went to that so you can see the power of this and the power of editing these photos I’m going to do one final one now what you see here is you see a lot of repeating actually there’s nothing wrong with this this is easier to understand especially when you’re first introduced to this module but we could do this a faster way as well now I’m going to create one for color I can say the value of this is image enhance this time color what do we want to add color to my picture instead of going to our next line I can just link my enhance method here it’s the same exact thing let’s say 2.5 again that’s a lot of color in our app right let’s just try 1.2 because we will be be able to continuously click the button to add more if we want to for here 2.5 we can take our color and we can save that new image as color PNG you can name your images anything but the extension they end with make sure it’s the same extension as the image you originally loaded I’m ending with PNG so I’m using PNG when I save the images let’s run this for the final time you can see how much brighter that got we added so much more color in there looks great we have just gone through and we’ve introduced and played a little bit with photos before you head into the next video I would like you to go find three photos these could be photos that you’ve taken off your phone that you want to try editing or photos online spend the next 10 or 20 minutes programming out a few more edits you can use what we talked about in the previous lesson or you can Google and do some research and read the pill documentation what can you find anything you’re able to add you’ll be able to add in your image editing app I’ll see you in our next lesson [Music] now that you understand how the pillow pill Library works it’s time to implement this to our photo app and in our last project the calculator app as a bonus part of the creation of that we did a refactor challenge where you refactored the app into a class-based application we are going to start from the get-go right now in creating our image editing app as a class-based application here I have two bullet points and each of these are actually two different methods that we need to create and I’ve worded these out before we look at the code to get our minds thinking about how this can be done and after I go through this in a file in vs code I want you to just type your ideas out spend 5 minutes what would you do what do you think is right to solve these we need to create a function now we want to create a function that’s going to filter through two two lists the first is a list of files and this will contain all of our photos and the second list is going to be a list of extensions so think about that what extensions do photos end with what we want to do is for every file in our file list we want to check to see if the file has one of the correct extensions now our photo extensions should have either jpeg PNG or SVG as there’re in image if they do indeed have one of those extensions we want to add them to a new list that we create within this function now as a hint I’ve given you a part of the code because this is a new pqt method we’ve never used before I can use this with a condition and I can say if the current file name I’m looking for ends with the current extension I’m looking for we can append it to a new list you’re going to start to see a lot of new methods actually I will do my best to explain them here in the lessons as you implement them into your code now that we have this first function done our filter function we want to create a function that gets the current working directory now if you aren’t familiar with the directory that’s okay let’s introduce you to that now you’ve probably seen this before in vs code when you run your code in your terminal it displays something like this right and this is basically where are you within your computer system users is like the main starting point at least I’m on a Mac the main start of a directory on a Mac is users then it’s the current user so what this would say is my path I’m on a Mac in the user Josh on the desktop in a folder named folder one in a file called main.py right that gets where I’m at and that’s called our directory in order to get my current working directory with pqt I can make a variable and the value is a q file dialogue and the method is get existing directory now Q file dialogue that’s a q do we import that what do you need to do for that think about that this function calls the filter function and we add the file names to our Q list widget on the app screen so this new function that you’re making is actually going to call the first function we made and it’s going to take those file names and it’s going to add it to our Q list widget as a hint here is the actual code we’re going to use this is the filter function we just made and it’s taking the current working directory with our extend iions this is our class in the last slide we introduced the two functions we need to create outside of our class which we are going to use to give a path or give a file to our class we Define four properties from the beginning because I know taking a look at some other important methods we need in our class we do need to create a method to save our image but don’t worry because we can still use the pqt or the pill save method but I want to create a method that is going to allow us to do so when we want to save an image we have to check right here I need to check if the path that I’m am trying to save my image as already exists so for example imagine you have a picture on your desktop called background then you try to save another picture as background we can’t do that you can’t have a picture that has the same name because they need their own unique path so first we want to check right here if the path already exists or the path is the current working directory if not then let’s make a new directory that’s what that says right there we can make a new directory and we can join that path with our picture then you can save that new picture awesome that brings us into actually loading our image so in the last slide we loaded a file but now we need to take that file and we want it to show as an image so how can we do that well let’s create a new method to show this image and this method will take one argument which is actually going to be a path where is this file we’re trying to show located remember in the original opening of the app we said the picture was going to be a q label so let’s hide that Q label it’s now time to show an image we can use the Q pixmap class from the QT GUI module and we’re going to give it the image we want to load which is our path once we have this image we want to give it a width and height which it’s just going to take the width and height of the CU Q label in our screen and then we can set the image and show our image set pix map and qpx map are coming from the module qtgui you must import qix map at the top of our code from this new module now that we pretty much have everything our class in the app generally are going to work but we cannot edit our photos remember if we click a button we want to have the ability to edit the photo based on the button we click we want to take what we learned just in the last lesson while you were experimenting with the pill library and bring that into our new application here is just one example of one of our methods so let’s let’s say we want to add saturation or add color to our image I create a property called self. image because remember my class has these properties we made at the beginning inside in it and it’s going to be given one photo in our class this photo no matter what it’s called we can call it and reference it as self. image the value of the image for this method is exactly what we saw before remember when we were introduced to the pill library and all the new code this is the same code the only difference is we are changing the name from pick to self. image all right after we edit the photo we can then call the save method that we just made we want to save our photo and then finally you want to show your new photo because this photo is new you need to generate a new image path remember let me go back actually I’m going to go back to the very beginning here we created a new folder called save folder this is the new path we need to use this now while we’re loading our new image I need to join together my current working directory my new save folder in my new save file all of these final three lines in every method you make are going to be the exact same you can copy and paste them because every time you edit a photo you want to do the same three things you want to save the image and you want to show it the only difference in the methods you are about to program you need to change what you want to do with that photo you can remember this and you can go back a few slides and look at what we did in the last video finally to tie everything together you need to link your buttons or your events do you remember from the first two projects how do we connect our events in pqt the object has the value of the class that we just made we can take the folder button and we can say hey python when this button is clicked I want to connect to the function we first made that allows us to choose the work directory then once we load all of the images we can take our file list and I want to access the image that I choose from the file list to do that we can make this new function and we can check if we select one of the items from the file list if we do we want to call the load image method we made inside our class editor this final function is responsible for loading the image we click from the Q list widget we have done a lot now before going into vs code you should go back through and review a little bit here and take some screenshots try and put all these pieces together in debug on your own I’m about to head over there and I’ll see you guys in the next video where we’re going to add the functionality to our image editing app I’ll see you guys there [Music] now that you’ve been introduced on how we’re going to add functionality to this app let’s Jump Right In and let’s do so to kick things off let’s focus on what we’re going to be doing and we want to be able to click a button and unlock your desktop or access your operating system and through this you’ll be able to select a folder from your desktop that we can open its contents and display within the app to open and unlock our operating system in pqt or python in general we are going to import the OS module OS stands for operating system we use this when we work with operating systems and finally in order to get an image into pyqt5 we are going to import something called Q pixmap qpx map comes from the qtgui module great we have imported OS and we have imported our Q pixel map looking great where are we going to add the functions and our class within our code well let’s go down to the very bottom all the functionality that we want to add will take place before the show in the execute methods so let’s jump in right here what do we want to do well I know that I want to filter the files and extensions we know that we want to choose or get the current uh work directory so where are we within our system those are going to be the first two that’s going to help us so let’s create a variable and let’s say working directory I don’t know what that’s going to be yet but I’m going to need that variable and then making a function for filter so filter is going to take a bunch of files and it’s going to take a bunch of extensions remember that these extensions are what our photo ends with so jpeg PNG SVG something like that I am going to create a list here CU I want to go through these files and extensions and I want to check that if they match if my file ends with the correct extension I can add this to my list let’s Loop through and let’s say for every file in all all my files I also want to Loop through every extension in all my extensions if the current file that I’m on ends with the current extension I’m on that’s a good thing I want to append that file to my new list once my Loops are done we can return my list okay so let me translate that I’m creating a list and I’m giving this function a bunch of files and a bunch of extensions I’m going to Loop through and I’m going to say for every file in the list of files it was given for every extension in all my extensions if the current file I’m on ends with one of the extensions I’m going to add that to this list and then finally return this list I want to use this function within another function I need to create a function that’s going to allow me to access my current working directory I’m going to say get work directory this is not going to take any arguments what I want to do here is I want to access this variable and because it’s on the outside and I want to change the value let’s make that a global variable in order to get my current working directory we are going to use a class from pqt called Q file dialogue let’s go up to the top of our code and let’s actually import it can be anywhere and I’ll say Q file dialogue just like so I can now use this in the function that we were just making get work directory so to access the current working directory I can take my Q file dialogue and say get existing directory just like so so now the variable working directory is holding my current working directory I’m going to create a list here called extensions and this is the list of all the possible extensions that my photos can have so I’m going to put these here for now and where these are going to go are they are going to be passed up to our filter function this is the list we’re giving and this is the list that we are going to Loop through because these are the accepted extension names every photo if you take it on your phone or if you take it on a camera it’s most likely going to end with one of these extension now that I have my current working directory and I have my extensions I’m going to create something called file names this is just a variable but its value is going to be whatever I return from this function so the value of this variable is going to be a list results that we get back what arguments do I need to give my function well we need to give it all of our files and all of our extensions where are we going to get all of our files well it’s going to be our current list directory or our current working directory so I can access my operating system and let’s use the list dur method function from the OS module and I can just give it my working directory that’s the first argument this argument is the same thing as my files the second argument I’m just going to give it my list that I’ve just created of extensions all right this looks good once we’ve done that I want to take my list where do we want these files to appear in our app well the correct answer is the Q list widget that Q list widget we have named file list right here I want them to appear here so I want to make sure that I have a clean slate or an empty list before I load in these new files going down let’s just say file list clear remember the clear method we learned this in the last project I’ve cleared my file list and I can now Loop through my new list file names remember that this is a list because the value is the list that we return so my list is called file names for every file name in my list of file names what do I want to do well I want to add every item that I come across to my file list just like so amazing all right we are so close here so we have our three starting functions we’re close to testing our app but we’re not done just yet all we need to do to run a quick test is let’s connect the button so let’s take our folder button and let’s run a quick test let’s use our clicked event so when the folder button is clicked I would like to connect to my get work directory function let’s run our app I’m going to click the folder button and try to load something from my desktop it’s working right so when we click the folder button we unlock our desktop you have the ability to go and select the desktop and choose a folder you want you just have to click the folder one time and click the open Button now everything within that folder I have loaded in my Q list widget these are all PNG photos you could have jpeg you could have anything that we specified right here as an extension awesome the app is looking great I want to have the ability to now click one of these and have it load over here how can we do that well let’s carry on and let’s solve that to do this we want to create our main class our class that’s going to store all the methods we make as well as be responsible for programming all of our buttons I’m going to close this I’m going to create a class and I’m going to call this editor editor we do need to have our Constructor and we need to ask ourself what pieces of information do we want to have inside our Constructor and not even inside the Constructor what information do we want to have access to within our class well I know that I’m going to have an image currently I don’t know what it is but it will have a value I will have one called Original and original is going to be responsible for holding the original image that we can go back to at any point in time I’m going to have a file name and lastly I’m going to have a save folder Where do I want these new photos to save this will be an extension of your current path so let’s just call it Edits edits is going to be the name of a new folder that we start to save things to let’s start with all the important methods we need a method to load images to save images and to show images let’s start with load an image this specifically will not actually load the picture in the app but it’s going to load the file name that we can take and then we can load that file name into our app as an image this method load image is going to take self as we need to remember self is like a key it unlocks our class and it will also take the file name that we want to load in our app let’s turn that file name into a property so I actually already have my property I am taking that same property and I’m changing the value To None to become whatever we give this function so my argument becomes the value to my property self. file name all right great next we need to create a name so the full name of where we’re trying to access and I can do this by connecting pieces of our working directory to do this we can access our OS module and we can say I want to join together I want to connect two paths or two directories together so OS path join I want to join together my working directory of where I’m currently at and my file name just like that after I have this new path called full name we want to open this so I’m going to take my property self. image that we’ve created up here currently its value is none who remembers how do we open an image I want to use the open function but I can’t just use open alone I need to use the pill python image Library so let’s go to the top of our code and let’s actually import pill I’m getting ready to use it from pill I want to import image what else will we need for this well I might as well import my other two classes now as well image filter and image enhance look at this we are creating this app and we have used three modules I’ve used OS I’ve used pqt and I’ve used pill they’re all working together to create a single application pretty cool now that we have image let’s return to our class I can say image. openen there we are what do we want to open well I want to open my full name right this is that path I want to open this image now as a file we have our image and before I edit the image or do anything I want to make a copy so I’m going to take my property original right here currently its value is none but I’m about to give it the value of my current image that I just loaded what do I want to do with this current image I want to copy this image now anything I do to the pictures through editing I always have a copy of that original image load image is done what is the next method that we want to do well let’s make one to save our images that’s what this is going to be responsible for every time I edit an image I want to have the ability to save this image within our new save folder how can we do this well let’s create a path and let’s say this path is equal to a join path and we can join together our working directory and at the end of the working directory I want to just link on the save folder so for example if my current directory is users SL job SL desktop now I’m going to link on my new folder edits right here that’s what we’ve just connected those two together we have our path I now need to check to make sure that this path does not exist so does this path exist or is this the current path so OS path is dur is the current directory okay if it’s not I am allowed to make a new directory with that name of my path I can create a full name again and just like before let’s say OS path join but now the question becomes what do we want to join together well I want want to connect this New Path I just made and at the end I want to connect my file name that property we can take our image and let’s call the save method what do we want to save I want to save my new path that we just made amazing all right we have our load image we have the save image before we do any type of editing we need one last method to get everything working this method is going to be responsible for showing our images so let’s call it show image this will actually allow an image to appear within our app screen this will take the path of the image that we are trying to load the first thing we need to do is the place we want to load the image is at actually a q label we don’t want to see that Q label anymore so our Q label is called picture box let’s hide the picture box taking that away from our screen next up let’s create an image and this is going to be an object of our Q pix map class that we just imported qix map allows us to load images into Pi Q UT it takes an argument what do we want to load well this path so I am giving a path to this class qix map and QX map is converting this path to a real image that we can show the next question becomes how big do we want this image well let’s actually load our app again I want the image to take up all of this space this space remember is 80% of the screen and we said that because when we created our layouts up here I Justified it as 80% of the screen so column 2 is 80% in column two it only holds our picture box in our show image let’s create two variables width and height let’s say the width is going to be the picture box width that’s literally the width of the whole column two and the height can be the picture box height and that’s going to take that what can we do with this now well I can take the image that I’ve created right here in line 119 and this image I want to scale it so I’m going to take the image and I’m going to scale it how big do I want to scale it well I now have a width and height that that I can scale it too an image that we load could become distorted and I don’t want that I want to prevent it from being distorted or weirdly deformed in any way to do this I can actually use the QT module and remember in the past we have used QT for our alignment well here I can use QT to keep my aspect ratios of the picture this will prevent the picture from being deformed in any way we now have an image that we are ready to load I’m going to take my picture box and I’m going to set pixmap what picture do I want to set to the picture box well my image my image is now set to the picture box but remember originally we hid the picture box let’s say picture box I now I want to show you again everything is done before you run the app this is all within a class so this isn’t going to work just yet we need to do a few more things on the outside let’s go on the outside and let’s create one final function this function is going to be responsible to display the image that we click from our file list so whatever image we click in this function we want to check to make sure that our file list actually has items in it and so I’m going to say file list the row has greater than or equal to zero there’s something in the file list if that’s the case I would like to get the value of an item that I click let’s create a variable called file name and we can say okay the file list. current item this will be the current item that I click on I would like to get the text value of that item and I want to use my load image method right here because I have a file name right I just made that I’m going to give this file name to my load image method how can we do that it’s a method well before moving on I’m going to create an object let’s say main I’ll say editor all right I have my object I can say main do load image now what do I want to load well my file name then I would like to show the image that I’ve loaded what do we want to show well I want to show my OS path I need to join together the working directory with something else with my main file name I need to connect those two this will allow our image to load great the final stage is we have an event for our button well now we want an event for our file list so I’m going to say file list when the current row is changed we want to connect with our display image function amazing let’s give our app a run the app is working I’m going to go through and select a folder now that I have the folder selected I can choose one of these images boom look at that I have loaded an image into my app I can select any of these images and they are loaded into our app this is great well done the functionality is coming together what do we have left well our buttons don’t edit these photos so let’s head over to the next video and let’s add the editing power to our app I’ll see you in our next [Music] lesson [Music] our app is coming to life in this stage of the creation of our app it’s now time to add the functionality for the editing so when we click our buttons I want to be able to add more color to a picture or convert a picture to black and white let’s program all of our buttons let’s scroll down to our class editor and in our editor class we have our load image method that’s great I load an image I can save an image we have show an image I’m going to go down here and I’m going to start to create all the editing tools we have so let’s just start with our first method and I will call this gray now this method we are going to program and it’s going to be very similar to the lesson we had that introduced you to the pill module if you go back a few lessons to the lesson that we spent time practicing and introducing the python image Library we want to use the same idea and the same Core Concepts in programming our methods so I’m going to take my image remember we made a property called self. image this currently holds the value of the image that we loaded into our app and I want to change that image I want to convert this image so I can use the convert method and give it the argument of L so I’m changing the image to Black and White Once I have this new image let’s say self and let’s call our save image method so I can save this new image into my edits folder that we created it next up I need to create myself a new image path because I want to show this new image and this new image it has A New Path because we generated a black and white image and we saved it into a new folder with a new name this new image path well I want to take my path and I want to join together what do we want to join together well my working directory with my save folder with my file name that’s a new path we can now take our show image method and we can
show this new image path that’s it that’s our gray method we edit our photo we save the new photo we show the new photo that is what’s happening in this editing function now that we have that the only thing to do to test if this is working is we can go down and we need to create all of our events the final step is I need to take my black and white button when that’s clicked we want to connect to our gray method that’s inside our class we can now give this a quick test before we write any other methods I’m going to select a folder now that I’ve loaded everything in let’s choose one I’ll choose a colorful one here okay this is pink I’m going to click my black and white button ah voila it is working it has been converted to black and white that’s great all right let’s work on the other buttons I’m going to close my app let’s trash the terminal now all of the methods are actually the same thing except what we are doing to the image but the idea of saving the image creating A New Path and showing the image that’s the same for every button so for example if I just take this method and I’m going to paste that here let’s change this to say uh left and take our image now and let’s change what we want to do to it so do you remember how do I rotate an image left right well I can take my image and I I want to transpose that image as the argument I’m going to take my class and Link the property rotate 90 that’s it we have a new method it’s the same exact final three lines we just need to now connect our left button all right I want you guys to pause the video here and I want you to program the rest of your buttons use the knowledge you gained with the python image library and use the knowledge from these first two methods to complete this challenge pause the video now I’m going to go through and I’m going to program the rest of these I’ve just finished up programming the remaining methods and as you can see here we have our gray left right we have mirror sharpen blur color contrast they’re all doing the same thing in the end the only difference is what we’re doing with that photo specifically the final step is each method needs to be connected to its button at the bottom of our code remember take our button when it’s clicked we want to connect with one of the methods that we made for that button everything’s working let’s run our app and at this stage 80% of what we’re trying to accomplish is done here’s my app I’m going to load a new folder now that I’ve loaded the folder let’s start with python so I can click left o there we go let’s click right that’s working mirror it’s flipped it our buttons are working we’re editing real photos with our code let’s do color if I keep clicking it you can see that it’s getting brighter and more colors being added if I click contrast it’s contrasting and then finally blur will be oh it blurred well I thought that may be tough to see with the python image right if I take it I click blur again it’s become blurry black and white loses its color our app is coming together and this is the most advanced app that you’ve created yet the last thing we need to do is we need to program this filter box to apply a filter remember that we can apply a filter it’s not going to save that as a new photo we can apply a filter and see if we like it before before we edit the photo in order to do that we’re going to introduce a new and popular python topic which is slightly Advanced and that’s the topic of Lambda functions I’ll see you guys in the next video where I will introduce Anonymous [Music] functions [Music] as we approach the end of our project it leaves us with one final task of adding functionality we have not programmed our filters or the filter drop-down box and that’s what we’re going to look at here in this lesson but to do this we have so many filters I don’t want to create a method or a function for each filter cuz that’s repetitive and we sort of did that just in our class I want to create Anonymous functions that I create and I use them right when I create them those are called Lambda functions this special feature comes with python and it’s for creating Anonymous functions which are these special functions that don’t really have a name most of the time when we create functions we do Define a name so we can call on them later but with Lambda functions we create it right where we need it and we call upon it immediately to run so they don’t need a name this is called Anonymous functions or in our case with python Lambda and this is a slightly more advanced topic that we are getting to explore let’s check out two live Lambda code examples I’m going to explore the first code example up here I have a function called Cube and cube is an anonymous function cuz yeah in this case I have given it a name but when I call this it’s going to run instantly now I’m saying it’s an anonymous Lambda function and I’m giving it something here this something is used in our expression what could these be in Lambda Lambda is taking a single parameter in this example I am justifying a single parameter and then that parameter is used in the expression of the function or what we want to do so four is really saying 4 cubed let’s add some color coordination in the bottom example I’ve actually written out a scenario so imagine you have your math problem you’re trying to solve by multiplying two numbers instead of writing a function for this somewhere in your code I am writing the function in one line right when I need it and that’s going to solve this specific problem now because we’re multiplying two together I am giving my Anonymous Lambda function one two parameters if I have have my two parameters we’re giving it two arguments when we use it these are being used in here so if we ran our code what would be the output of both of these Anonymous functions well the first output would be 64 and our second output would be 15 so you kind of have a core understanding now of what is Lambda what it accepts and how we create a basic Lambda function but how can we use this our project well let’s break that down a bit more our mission with Lambda is to create an anonymous function for each filter that we have in our Q combo box so I’ve kind of given you a head start but how could we do this with a dictionary because it seems very repetitive and I’m going to have a lot of these filter options so instead of creating these in seven lines or however many we have why not store them in a dictionary now remember a dictionary key value and what this would translate to is dictionary key unlocks a value so we can use that to structure our dictionary hm that’s interesting what would this look like in our code here I create an instant Lambda function and when this is used it’s going to be executed and ran immediately this is a dictionary filter mapping and remember in a dictionary we have a key and every key has a value together these are called our key value pairs so the key is actually the text from our drop-down box and the value is this Anonymous function that’s going to take an image the image that it takes it’s going to convert that image to black and white that is really interesting that makes our code run a lot faster and it allows us to create these little functions that we want to call upon throughout our program and you can see for every item in the drop- down box I’m making a key value pair which represents the drop- down box name and a Lambda function here is the overall function so let’s say we create it and we name our function apply filter I am going to give one parameter of a filter name this is the name that we select from the drop-down box if I click black and white then black and white is going to be given to this method the first thing I want to do is I want to check if I chose original because if I did I want my image to actually be the copy that we first made when we loaded the image I want to revert to the original copy if we do not choose original it must mean we did something else so here is our dictionary of everything else that we have the ability to choose from our drop down box each of these Keys has an anonymous function that will be executed instantly and they all take the same parameter image which you can see are being used within the anonymous function now this dictionary nothing is happening if we get to else we are going down here and we’re checking right we want to get whatever the filter name was from our dictionary remember that this filter name is actually the parameter that we gave we can check to make sure that yes we do indeed have text from our dictionary and we can go about our day we can set our image to whatever image we chose from our dictionary we can save that image generate a path and show the image just like how we created our methods in our class inserting the dictionary taking the value of the filter function is whatever the Lambda function returns if Lambda returns something we want to show what lambdaa returned let’s jump back to our code and let’s implement this final apply filter function and get you guys reading your first Anonymous Lambda functions I’ll see you in the next lesson [Music] now that you’ve been introduced to Lambda in Anonymous functions let’s create a method that’s going to store many Anonymous functions and these functions will be responsible for applying our filter let’s scroll down to our class and in our class we can go pretty much towards the end actually let’s go all the way down before the final one so I can go right in here let’s create a method that I could call this apply filter needs our word self and then what do we want to give it well I’m going to give it a name more specifically whichever word that I choose from the drop- down box I want to take that text value and I want to use that within this method so I’m giving this method a text value from my drop down box let’s just call this filter name the first thing I want to do is I want to check if my filter name is equal to original because if it is I want to revert or change the image back to the initial starting image I can do this by saying okay cool self. image in that case is equal to self. original. copy so our image is equal to the copy that we generated earlier great that’s why made the copy to be able to go back to the original copy else if it’s not original then okay I have selected something that I want to actually apply a filter on now in our drop down box if I were to go check we have all of these so 2 4 6 I have eight different options and each option is going to be able to do something or have its own function so the best way to do this would be to create a dictionary where each of these would be my key and the value is going to be a function that’s triggered only one time that’s why we create a Lambda or Anonymous function I’m going to return to our method that we’re making and let’s create a dictionary let’s say mapping now I need a key in the first key let’s just start with black and white and let me make sure these the text value needs to match what we’re trying to do so black and White’s good make sure your spelling is consistent returning black and white and the value is now going to be a Lambda function so to create a Lambda function we’re going to use the word Lambda then I need to justify any parameters my function will use the parameter well it needs an image that it’s going to edit so this function doesn’t have a name because it’s only being called when I get to here so it’s a function it’s a Lambda it’s Anonymous it has no name but this Anonymous function it does have a parameter which means I’m going to give it an argument next up in the function it is going going to take what I give it and it’s going to convert that image to black and white that’s what it’s going to do one and done all right so next up let’s try one more together let’s say color color is going to be a Lambda function it takes a parameter of an image let’s take what we give it and let’s say image enhance do color what do we want to enhance the color of well the image we give it how much do we want to enhance it by let’s say 1.2 just like when we programmed our method above right here same thing I have now created two Anonymous functions I want you to try to program the rest of these Lambda functions on your own pause the video here I’m going to go through and I’m going to complete the rest of these Lambda functions what do we want to do to that photo the New Concept though is creating an anonymous function now remember that this Anonymous function is a special python function that doesn’t have a name and it can perform any task we assign it without needing a name as well so I am giving a parameter of image and we are taking whatever we give it and we’re going to apply and edit to it great so I’ve created this dictionary now and my dictionary is called mapping well I now want to map over this and I want to get one of these I want to get the one that is equal to my filter name let’s create a function let’s say filter function and the value of this is I’m going to take my dictionary and I want to get what do I want to get well I want to get whatever the filter name parameter of this method is that’s the value of filter function I now want to check to make sure that there is a value that we selected so to do that I can just say if filter function right that translates to if filter function equals true or if there is something in our filter function if there is what should we do well let’s take our image right our property self. image and we’re going to say hey I want to update this and I’m going to update this to the value that we gave our filter function self. image I can then save let’s call our save image method I can create an image path just like we did in our initial method so OS path join we want to join together many things working directory our save folder and then finally our file name what do we want to do last well then I can show this new image that we have kind of created or at least applied the filter to so image path uh finally if that fails let’s just say pass I want to skip over it so our apply filter function or I should say method is done we have a method and this method contains about eight other functions which is incredible now that most of the supply filter method is done we’re pretty much there outside of my else right so no matter what when this condition is done running I would like to save the image so let call our method we made save image let’s take our image path and let’s show our image so I’m going to take those and I’m going to put those just like that right there looking great we want to create a function on the outside to handle any of this so let’s say let’s create a function called handle your filter and the first thing we need to do is we need to make sure that indeed there are items that have been loaded into our Q list widget so just like we did in the other one let’s make sure that we have an item what do we want to do with that item well I want to get text so bear with me Whatever item I click from the drop down box I want to get that text in order to do that with a Q combo box or a q drop-down box we do not use the text method instead what we can say is let’s take our filter box and let’s use the method current text now that we have the current text value let’s call the apply filter method giving it the text that we just created or got our final stage is we need to create our event for our handle filter method we can take our filter box and we can say hey when current text is changed we want to connect to this new filter function now the current text the current text is initially original because it’s the original photo when we change that all right now we want to trigger this event amazing let’s run our app I can now load in a folder and let’s go through and choose one of our images so let’s choose a this will be perfect in my drop down box I can now choose how would this look as a black and white image oh that looks pretty good okay let’s go back to the original great now how would that look if we blurred it well I can’t really tell right so I’m gonna go back to the original again everything is working this is great well done you guys have a completely working image editing app that we’ve created we have accessed our desktop using the OS module you’ve used multiple modules from pqt and we’ve used a few classes from the pill module as well to achieve this well done I’m so proud of you guys if you’re interested head over into the next lesson where I’ve prepared a special challenge using Lambda to extend the functionality of our photo QT image editing app I’ll see you in the next [Music] lesson congratulations we have a working image editing app for fully completed with the editing capabilities that we wanted as well as Lambda functions now let’s refactor our code and I’ve prepared a challenge for you guys using Anonymous functions to make our image app more efficient let’s take a look currently we have a class and our class has all of our editing methods in right so every button we have we created a method for I want to see if you can take all these editing methods and convert them into this can you replace all the buttons and how can we use Lambda to do so I want you to try to create a new method which is going to replace all of these you can name this method transform image or if you have a better name use that name this method will hold a dictionary just like our previous method with all these functions we want to replace or I should say update if you’re up for a good challenge this is better going to improve your understanding of how to use anonymous functions as well as using dictionaries I’ll see you in the video where we refactor our app and add in this final method [Music] you must be up for the lamba challenge if you’re here and I’m glad you are we’re going to refactor this code and make it significantly more efficient and less all while keeping the same functionality let’s take a look right here we have all these buttons and we want to create a Lambda function for each button this is going to be very similar to how we created them for the filter let’s take a look at our class we have our editor within here we have in it we need that we have load image save image show image we need to keep all those because they each have an instrumental task that is called upon at some point in our program but all the other methods the ones where we create the actual editing techniques you can see here that I have 1 2 3 4 5 6 7 eight we have eight of those what if we could replace all of those with a single function well that’s what I’m going to do I’m going to take all the methods that we just programmed and I’m going to delete them from my code what you can do before you delete is maybe make a copy to keep this and you’re able to see how far you’ve come and we have a starting point which is this and now we’re progressing into more advanced concept so I’m going to delete those we have our apply filter method currently now I have if we go down to all of our events we have none of these anymore right main mirror mirror is not a method we just deleted that let’s go up here just above our apply filter method we are going to make a new method here and we can call this transform image transform image is going to take something so transformation what do we want to do to the image if I click the blur button blur is my transformation it is very similar to how I explained filter name in the apply filter method inside here we will make a dictionary this dictionary is going to be structured the same way as as we did here so I can actually take most of these out let’s just copy those paste those here what do we have 1 2 3 4 five six seven eight those are all of our buttons as well and just double check that these text these strings all match your button names at the top and if I do a quick check they do match going back down to this new transform image function we have a dictionary inside that each of these is a key value pair the key is what the button says and the value is an anonymous function our Anonymous function will take an image and it will do something with that image we have all of our functions ready to go in our Transformations dictionary let’s create a a transform function and let’s just say I’m going to say Transformations I want to get the transformation I give as the parameter this is my dictionary I want to get something from the dictionary and I want to get the original parameter we passed into our method just like our apply filter method I’m going to check to make sure this is true I indeed have something because if we don’t have anything well I can’t quite do anything with it if I do though I’m going to take my image and I want to update my image this is now my image after we apply our filter to it we can save this new image finally we can show this new image just like that I have replaced all eight of of our original methods with a single transform image method all that’s left to do is we need to connect our methods to our buttons and because we’re using Lambda this is going to be slightly different where do we keep all of our events well they’re at the bottom let’s head to the bottom starting with our first button gray now I’m going to change what we’re connecting to we are connecting to a method but that method is a Lambda Anonymous method or it’s an anonymous function in our method transform image Lambda is anonymous I can take my main object that’s my class remember and to our main class we can link our method we just made which is transform image I now need to select one of the keys in transform image so if I go up here for the gray the black and white this is my key I’m going to use this in here I can just say black and white if I go to our next one I would do the same thing I would take Lambda and I would say our object let’s transform our image and I think we just called that one left if I go up and check yep right there left I’m going to go forward and program the rest of these all right we have all of our new Lambda functions connected that means it’s time for us to run our app all right and just right here so I’m trying to show an image but if we remember show image takes a path which I’ve left out here so let’s come out here I’m going to do a few things outside I can do save image again then directly inside let’s create an image path again and we can say OS path I want to join what do we want to join well I want to join my working directory I want to join my save folder that we have created so save folder and then finally our file name and we can just do a check does this match this it does our app is running selecting a folder going down to our images left great it’s working right there we go I can mirror it I can add color to it there we are contrast all of our buttons are working they look great amazing we just refactored our project to more efficient code you have been introduced to so many new Concepts in this project one the introduction to a new module pill the pillow library for working with images two you have now been introduced to Anonymous function in Python which I’m sure you’ve seen before these little guys are called Lambda functions as well as taking your pqt skills to the next tier amazing job congratulations I’ll see you guys in the next lesson for the start of our next [Music] project [Music] congratulations as we enter our next project you guys have done an incredible job you have so far three fully working apps with one warm-up or introduction app for pqt you have a fully working calculator applic and after completing the last project you now have an image editing app as we enter this project you are about to make an expense tracking app but this app is going to do so much more than just track your expenses and use your knowledge of pqt not only are you going to use and build on all of your pqt knowledge you are also going to get an introduction to SQL and how we can incorporate SQL databases into our app to track and maintain live data more specifically live data that’s changing so in the last project you got an intro to Lambda in Anonymous functions add that to the CV in this project you’re going to get an intro to SQL and what that is and how we can use that with apps let’s take a look this is our overall app overview our app we have the ability to add expenses delete expenses and also save data in a database and I want you to think what widgets are you seeing on the screen you should know most of these right we have been using these in previous projects so what widgets do you know well let’s take a look all of these widgets we will be using in our app and you can see right from the get-go there are two that you may be unfamiliar with as we haven’t used them before we have our Q date edit in Q table widget now you can see that the date edit is collecting a date we even have a category that’s going to allow us to choose what category our expense came from we have the ability to enter the amount of the expense as well as a description of what we spent it on we create two buttons and at the bottom here we have our visual database so this is the front end of what we see once we add all of our data using SQL to our SQL database have you thought about your design yet because as you’re growing more and more of an expert with pqt you should be thinking about your design every step of the way how could we design this app well let’s take a look I have created one map Master column and you can see I’m using QV box layout I have three rows at the top with a few objects in each row my table does not need a row because it’s going to take up my whole screen everything else I want is actually above my table while you’re designing this app you know most of the methods and the ways that you will be able to implement your designs but C table widget this is new and you will need to import this along with your other QT widgets in order to get your table set up there is a method that comes with our Q table widget class we have set column count and this takes an integer as an argument and you can see that in this example we have five columns if I put the number five inside here we will see 1 2 2 3 4 and 5 that allows us to structure our database and get it ready to accept data the second method that we are going to use is called set horizontal header labels this method takes a list more importantly this list is going to have many elements each element will be a string and the string will be the name of your columns if you say you have have a column count of five then in your list you should also have five elements each element is representing the name of your headers the name of your rows let’s head over to vs code and let’s try and get our app designed and structured before we dive into SQL I’ll see you over in the next lesson [Music] now that we’re here in VSS code let’s get our expense tracker project all set up and designed you can see here on the screen this is what we’re aiming for and by the end of this video we will have an initial design something like this ready to go let’s move that away for now I have here my code burger and what do we need in order to design this app well a lot of things but in this video we are just going to focus on one module QT widgets because we need to design our app first and that’s what we can start things off with in the previous projects we have created an app then converted that or refactored it into a class-based application well to kick things off with this project we are going to start by creating our application as a class-based application let’s begin here with all of our Imports so from PI qt5 QT widgets we have that one down let’s import our Q application we can import our Q widget what else do we need in our app so if we take a look at it what do we see here right I see Q labels I see q line edits I see our Q combo box I see an area for our date and time we have a table a few new widgets we need to import all of these so let’s begin I know that I’m going to have a Q label we saw a q push button there we saw our q line edits we can bring in our Q combo box then our two new ones we had a date edit window and finally let’s just come down here I’m going to say Q table widget now I’m going to put that back on the line there we are Q table widget anything else that we’re missing is there anything else we need well don’t forget QV box and qbox even if you don’t know if you’re going to need both layouts it’s always good to import them because there’s a high likelihood that you will let’s create our class let’s create a class called expense app inside we can create our Constructor as this is going to run immediately every time we create our app so when our program runs it creates an instance from our object and this init Constructor will immediately run we need to ask ourself what do we need well our main settings we usually like to use resize but I don’t have any main window and in order to get that let’s inherit just like we’ve done before let’s inherit Q widget now that I have q widget I can refer to myself and we can say okay let’s resize and let’s give ourselves a window title because we always want to give our app a title we can call this expense tracker 2.0 the window size let’s give it a size of 550 for width and 500 for height that’s a good starting point now we need to create all the objects we see on the screen remember the input Fields the table the date box all of those items so let’s create one let’s say datebox and datebox will be one of our Properties or an object that we’re creating now for the app UI and a date box we can say Q dat edit just like so we also have a drop- down box so let’s just say drop down and this is our Q combo box we have our amount which is going to be a q line edit and then we have our description an area that you can enter what you spent that money on and that will also be a q line edit now we did have text within the app but that’s going to create too many objects and the text I won’t need to do anything with that value so I’ll actually create it here when I create my design speaking of of design we need to justify our Master layout I can create my object Master layout and I know that everything here will be held in a column so let’s say QV box we have that and within that column we are going to have let’s say Row one row two and Row three bringing those down just remember to change the name of your property all right what else do we need we have our all of our input Fields I know I’m going to have a few buttons on the screen so our buttons will be an add button to be able to add to our expense so we can say that would be a q push button add expense we will also have a delete button this delete button will once clicked we’ll remove from our table we have almost everything that we want to see this brings us to our final and our new object we are introducing SQL in this project so with SQL I want to be able to display all my data within a table we are going to use our Q table widget let’s create a property called table this can be our our Q table widget we can do a few things with this in the beginning when I’m creating this table let’s take our object I would like to set the number of columns this will help us with our SQL queries and adding data at a later stage let’s use the method of set column count in here I’m going to to have five rows of data which we will see here shortly but that’s going to look like an ID a date category amount and description that is why we have five columns once we have this then we can take our table I’m going to call the method set horizontal header labels because I want to give a title to each column that we create this will actually take a list we can do this two ways I can say header names making a list what do we want our header names to be let me code these out I now have a list of my header names you can see these are my column names just like before I created five columns in column one that’s my ID column column 2 is my date our method set horizontal header labels that takes a list so header names did I have to make this no I did not I could take this I could just put this inside here like this how I did it before was easier for readability we have a table now with five columns and the columns each have their own name we’re ready to go what do we need now I have all my objects next up in our code Burger I can actually structure this so there we are we can design our app with our lay layouts what layouts will we be using QV and qh box let’s create a master layout that can be my QV box then within my app I know that I’m going to have three rows so Row one qbox layout let’s create the other two we have our Master layout along with our three rows ready to go now that we have these let’s go through and Design Row one I want to start with you I want to add some widgets to row one in case we forgot what we’re aiming for in our app in row one I’m looking for these date text the date time box our category text and our Q combo box notice I didn’t actually make Q labels and that was to save us space in our code as we aren’t going to do anything with these values vales so I can immediately add these to my layout what do I mean by that well right in here I can just actually add the class Q label what is this going to say well it’s going to say date like that so I’ve added my widget next up in my Row one I would like to add what do we want well I would like to add my date box after these we can add category text followed by our Q combo box which is what we called drop down so Row one is completed going on to row two it’s the same idea I can take this as a starting template and instead of Row one change that to row two our Q label that we’re going to be putting on which actually right here this should also be our Q label instead of saying date here we can actually say amount what do we want add next to amount well let’s add the widget and let’s say self. amount that was our property that we created here of a q line edit the final two all right row two is completed Row three we just want to add our two push buttons to them great our three rows are designed and all ready to go what does that mean what do we need to do with our rows let’s add the rows to our Master layout so take your master layout use the method add layout you should have this under your belt by now adding in row one we can copy that as we need to do it three times one two get them all set the only thing we have to do is change the layout that we’re adding so self. Row 2 self. Row 3 let’s set our final design usually we would do something like this but where is my main window I don’t have a main window remember my main window is my super class so I’m going to refer to my S and I can say self. set layout I want to set the master layout as the main layout all righty our design is almost all the way there currently there’s no table on the screen we’ve added our three rows to the screen then we did set the final design but right in between here before I set my final Design This is where we want to see our newly created table let’s add that but the table is so big I don’t need it in a row it’s going to take up the whole row itself it’s just going to go at the bottom of our expense app all we need to do for this is take our Master layout we can add widget and we can add our table because we have created our class base application let’s go on the outside right here and we can say if name in main we can create our app Q application give it an empty list here you could create something just an object and what is our app class expense app main. show app. execute let’s run our app and see if it’s set up the way we want it to be all righty so right in here it’s telling me that I need to activate my super class which that’s actually true I buzzed right over that going up remember anything that we pass in so I’m inheriting the super class let’s use the handy python super function and say hey super I want to initialize you just like that give our app one more run there it’s all taken care of here is our app ready to go everything is where we want it to in our three rows with our new table at the bottom spend the next five minutes and tweak any details you may want to tweak if you want to change the words change the header names change your alignment that’s up to you I’ll see you guys over in our next lesson where we will introduce SQL in pqt [Music] now that your app is all set up and ready to go it’s time to introduce the top IC of SQL and how we are going to use SQL light with the module QT SQL to work with our app in pqt if you’ve worked with SQL before great you have a head start and if you’ve never used SQL before that’s okay because I’ve structured this lesson as a breakdown to what it is and how we can use it it’s going to ease you into working with SQL let’s jump in so SQL really means structure structured query language you might hear people say SQL or more commonly SQL now we’re going to look at three SQL keywords and this is basic Syntax for SQL these words these key operators are used in the SQL language select from where notice that all of those are capitalized that’s very important we use the select operator to select the column colum we want to look at we use the from operator to choose the table where the data lives that we’re trying to look at and we use where to justify a specific condition so when something is true that’s what we want to find with our data so picture this we have an example down here picture I have a table that has the name users I have two two columns in my table I have a username column and a password column then I have a condition that I want to look for the username Mario 123 I could write my query in two ways up here I’m writing a query I am saying select star which literally translated means select everything from my table remember my table is called users so this literally says I want to select everything from the table named users but that doesn’t do it right because I have a condition so I want to be more specific I’m looking for a username right well select the column named username from the table named users where my username is equal to Mario 123 that’s allowing me to access key components of my database and pull out the data that we are looking for we are using SQL and we use this to work with our relational databases or these are databases that store our structured data within tables let’s take a look at how we set up a SQL Connection in pqt before I move on remember these three key words from SQL select from and where and try and remember these two examples and how they relate to our example here let’s take a look at how we can set up a SQL Connection in pqt in order to create a connection to SQL light we are going to import something called Q SQL database we can import this from QT SQL module I am adding a database what type of database is this well it is a SQL light database which is a lightweight database for working with SQL in Python I am justifying that as the value to a variable or an object of database I can give my database a name giving it right here making sure my extension is DB these are the methods that we are going to see here I can use add database to create my connection I can use set database name to set the name and we are going to use the open function to open our pre-existing database so that every time we load our app it’s going to load all the data that we’ve previously stored in our database you can see I have a condition here now let’s just start with the very Basics I have a database so if my database is not open I want to print off error I’m going to talk more about this in the next slide but the key component here is I’m creating a condition just to make sure that indeed I do have a database and I can open it if I don’t have a database and I can’t open it I want to print off or alert the user to an error now you can see I’m using something called Q message box simply put in pi QT a q message box is just a popup box any of these popup boxes can look like the following you can see they’re all different but they’re all little windows that can pop up on the screen and each method we use with Q message box so for example I want to ask the user a question you can see that it kind of has a question mark warning warning critical critical there are different things that we’re triggering we can use to ask the user questions as well and based on the response of the user we can do something with those but let’s focus on the bottom two right now because it’s just a pop up and it’s just alerting the user to something remember that those methods are linked to what type of Q message box we are seeing now that we’ve created our connection to our database remember from the previous slide database was created and we open our sqlite database let’s create a query and we want to run our query to create a table named expenses but we want to check first to make sure it doesn’t exist so a query is basically a question that we are asking the database I’m preparing to query or ask the database for some type of information so I can create an object and I’m going to import qsqlquery this is used to execute any queries on our connected database then I can use my query and I can execute a question or I can execute a query to my database this structure inside is actually quite important okay all of this is a string and this is how we can use SQL light to perform queries in Python we are saying Hey I want you to create a new table if it doesn’t exist and I want you to name that table whatever you say here expenses we are giving an ID now these items here are the columns in our database so the First Column is going to be the ID of that item in our database the second column is going to be a date and this date is going to be the value type of text category it’s going to have a text value amount is going to have a real value a number value we use this execute method which you’ve seen before in pqt because it prevents us from needing additional boilerplate code specifically with SQL we can incorporate the code inside the execute method okay so take a look at what’s Happening Here We execute the SQL query specified in our quotation marks to make it a string and we create a table named expenses with the following columns ID date category amount and description each of those I’m also telling the database what type of data it’s going to have is it a text data or is it a number data let’s jump into our project and let’s create a database that we can begin to add things to where are we going to create our connection to the database and where will we create the query those are questions to ask yourself as we jump on into the code I will see you guys in the next [Music] lesson now that we have our database all set up it’s time to create our methods now these methods we’ll be building are specifically going to be built for our add and delete buttons when we click add we want to add our data to a database when we click delete we want to remove our data from our database let’s take a look at our first method before we even get to the ADD and delete methods we need a method for loading our table because every time we open the app we want to load our pre-existing data now in the previous projects I’ve put a lot of code examples on the screen but at this stage you should feel challenged or at least I want you to put in the challenge to problem solve and to logically solve these steps I have broken down step by step what we need to do to create the method to load the table and I am going to show you a part of the code in the next slide start to think about how we can do it using what we talk about now the first thing we need to do is we want to clear the current Table that’s because any old data I don’t want the old data to be there to do this we’re going to look at something called set row count I can then create a new query to select everything from our table using using our class Q SQL query you’ll create a loop and this Loop will run as long as there are more rows in the table right so if you have a database with 10 rows or 10 pieces of data your Loop is going to run 10 times until everything from your database is in your app once we do that Loop we can retrieve the values from each column we will use the Value method to do that the information we retrieve we want to insert the data from number four right that’s what we retrieved and we can use insert row to do that before increasing a row counter this method is responsible for displaying all of our database data in our app so we can visually see it how would the loop look I want to make a loop and that’s going to repeat and I want to use the next method with a loop that’s a bit odd well along with our query we do want to create a while loop so I can say while there is another row in my query that’s what that translates to right so while my database still has another row I want my code to run every time this Loop runs we are retrieving the values from each column column one column 2 column 3 column four column 5 if you have more columns make sure you retrieve those values we’re using the Value method that takes an integer once we’ve retrieved all the data from that current Row from every column we want to insert that data into our table so imagine you your table is called expense table you want to insert the current row that you’re on right so row needs to be an integer we need to insert the current row we can then go through and set the items of every row so I’m going to put my row number which would be the same for all of these and then I’m going to put the column in the row next is the information we want in that row now notice this is a new class but this is the item that we collected that we want to display in row one or more specifically in the First Column of our first row now we’re going to look at the added new expense method what do we want to do with this well we want to gather the info that we entered from the input boxes all the info the date the description the drop-down information the amount and we want to insert all that information into our database then we want the input fields to clear to prepare for the next input we can then load our database if I add or delete information I want to load that new database information so we can visually see it take a look at all these methods some of them we’ve worked with before others are new which ones look familiar to you do you remember why and how we use them in our code let’s take a look at what each of these will do for us I’m going to touch on a few of these I’m going to touch on all the new ones we haven’t addressed and if you need to pause the video screenshot that’s fine you can do that we have the prepare method we use use prepare when we’re working with SQL and this will check the provided query to make sure that it’s a valid question it’s a valid query so when we click a button I want to check to make sure that all my data is going to sit well in my database that is when prepare comes in hand we have the method add bind value add bind value will put the information in a column that’s in our database for us every piece of information we will need to use add bind value we can use the two string method and this will convert an object into a string we can use date and this will convert our input in our case which is a date into an actual date and let’s take a look at our last one here current date this will get the live current date in time like if I ask you hey what’s the date today that is what that that will return take a look at these remember these are all methods so think about the objects that these will be linked to how can we finish up our add function within our add new expense method the first thing I want to do when I click the add new expense button is we want to collect all the data from our input fields at the top of the app you can see that I’m collecting my date I am collecting the information from my drop-down box which is a category we are getting our amount and we’re getting the description using all this information that we just captured from the input fields we can create a query and we can prepare to execute our query now notice the seq syntax insert into so we can prepare to to insert into our table expenses what do we want to insert date category amount description date category amount description our information is going into our database every item we want to send off that info now so prepare it’s preparing to get the database ready to accept this new information now we want to send off our information to our database and we can do that using the add bind value and giving it an argument what do we want to send well I want to send my date off to my query and you can see in position one of my query is the first item that we prepared as well in position two of the query is the second item we prepared for our query all right let’s jum back to vs code and see if we can program out this add new expense method to make some SQL [Music] queries we have our app all set up and ready to go you’ve been introduced just on the surface to SQL and I’m excited to be able to implement that now into our application to create a real database that we can load in data delete and add data to begin let’s go to the bottom of our code here we have our class at the bottom that’s what’s running right this is where our app is running right here this is where we we can create our database before I can create the database we need to import that from our module going up here all we currently have is pi QT and the QT widgets module we want more than this we are going to say from PI qt5 the module we’re looking for is QT SQL we want to import to two classes or two modules from within I want the Q SQL database and we would also like the Q SQL query those two perfect outside while we’re creating our database here I can create a variable I’m going to call that variable database and I can say all right database is equal to Q SQL database dot I want to add a new database what kind of database is this this is going to be a q sqlite database we have this variable that is a sqlite database we can take it and let’s set the name the name I can call is expense. DB DB you guessed it stands for datab base we’ve created it I want to create and try and catch any error errors that might happen and the error that might happen is I’m not able to open my back end I’m not able to open this database for some reason if that happens my app needs to close it’s it’s not able to open without any data let’s say if not my database open so if I can’t open it I want a message to appear on the screen how did we do that before what did we use it starts with a q but we haven’t imported it yet Q message box let’s go and import Q message box at the top right there’s our Q message box returning now I can create this and let’s say critical because if this happens that is a critical error I can’t I can’t get past that my app can’t run without it our first argument can be none I’m going to say error within the app I can say could not open your database what do we want to happen I would like exit I want my app to just exit immediately exit is something that we need from another module this is the only time we’re really going to use it in our applications that module is called CIS or system we want it to exit after 1 second up at the top let’s pop in here import CIS now that we’ve created this database I can now create an initial query remember query is like a question or an initial setup so how do I want to set up my database what structure is this going to have I will create a object called query from the Q SQL query class I’m going to take this and I’m going to execute an initial query or run an initial query when this is Ram this is where we put all of our SQL syntax a lot of this is specific for SQL light here we’re going to put six double quotes drop down like that how do we want to set up this database well what I can say is I want to create a table if it doesn’t already exist this table is going to be called expenses or whatever you want to call that table that goes there okay so if I don’t have a table I’m going to create one and it’s going to be called expenses what structure will this table have if you don’t remember go up and let’s take a look here at set horizontal header labels this is the structure of our database let’s make sure everything is pretty much how we want it I can say ID everything’s capitalized the first thing that’s going to be in my database will be ID that will be in column one and so forth returning to our query let’s say the first one is our ID ID is going to take something called integer primary key autoincrement what this means is an ID I’m not giving it that information every new row of data it’s automatically generating a number so Row one row two Row three and it’s automatically adding in that number so that’s autoincrement this is known as the primary key the master key for that row let’s put a comma next up we have date what is date well date is is going to be text we don’t have to do anything mathematical with that value so it’s just text next up is category category is also text we have the amount amount is real real in SQL just means it’s a number we can do something with that value lastly we have our description and our description is text great we have our query all ready to go it’s set up in the order that it’s going to receive that data it’s going to receive it as an ID but it won’t receive that because that’s automatically being incremented the other four in order are being added into this newly created database every query is going to be structured in this order ID date category amount and description amazing we’ve created our first database in the app but currently we can’t do anything or we are not doing anything with it we want to be able to add and load from this let’s go up to our class we are going to create a few methods here the first method I want to create before I can add data or delete data I need to load my table into my app I need to load my database let’s create a method right here and let’s say load table it’s a method it’s in my class it’s after we initialize everything I can give ourselves a bunch of room right here to kick things off let’s take our table I’m going to take the table we’ve created and I’m going to set the row count we going to set it at zero this is one of the methods we introduced during our lesson during the previous slides we have our row count set I can create a new query a new question remember anytime I say query I’m saying question what do I want to ask it well I want to ask it to select everything from my table known as expenses please remember that these are special SQL syntax words expenses is lowercase because that’s the name of my table select is a word and from is a word from SQL let’s create a row because currently I haven’t loaded in any data but I want to start on row zero and begin after that so row zero Row one row two everything after that first row will be loaded in as well but we need to load in the first well we can say while my current query. next so while I have another row available still while there is another row in my table we want to get the values from each column in our row remember the order of our column let me bring back up our SQL query we have our ID date category amount description let’s go up now in order let’s get an expense ID let’s say the expense ID is just equal to our query value0 so it’s equal to whatever the first column in my database is because python starts on zero My First Column is actually zero in my database if you check the First Column is our ID so the value is whatever we get from our current row next up we can get a date we can say our date is query. value and I think you can guess so for each of these we want to get the value of that current column I’m going to go forward and I’m going to grab the values from each column I have our five columns and I’m getting the value out of each of those so every query runs we get the value from that column we’ve indexed now now that we have these values we want to put them into our Q table widget so I’m going to say add values to table we can’t see these values we can’t see what’s in a database I want to take it out of the database and put it into a table for us to be able to see let’s take our table property and we can say insert row what row do I want to insert well well I want to insert the first row which would be row zero the first time this while loop runs but I need to be able to increment that to go to row two Row three I’m just going to put my row variable remember we have our row variable here so I’m adding the first row I’m inserting the first row to my table at the end of this you guessed it we can increase the row so so every time our Loop runs we are increasing the row and adding in row two Row three Etc after we’ve inserted the row I want to take the values that we got back and I want to insert them into a column within my table to do this let’s take our table I now have my table object and I want to set an item in that table okay what row is this from I don’t know but it’s from the current row I’m on all right now it’s asking me for a column great the first one I know is column zero that’s the First Column then we need an item well to get an item here because we’re working with a Q table widget I’m going to go up and I’m going to import one more key class for us to do this at the top here let’s import a class called Q table widget item this is an item in a table you guessed it going down I can now use that new class I can say Q table widget item like so what is the first item in the First Column think about that for a moment what do I need to add inside here an ID well where’s my ID it’s right here it’s called expense ID let’s convert this to a string and let’s put in expense ID just like that so I’m taking my table and I’m going to set an item in that table it’s going to be in the First Column and it’s going to be my ID amazing I’m going to copy this how many items do we have we have five so one 2 3 4 five there are our five items let’s go down let’s change our column numbers and also the values here what do we need here well I need a date I need my category I need my amount and amount is a number so I’m going to leave it to convert to a string here our final one our description if you need to pause to understand what’s happening please do read through an interpret in your own way once we’re done here I’m going to read through again and translate what’s actually happening let’s bring our row up and we are ready to go through this method let’s break things up when this method is called we are setting our table row count I’m then creating a new query I’m getting ready to ask my database a question what’s my question going to be well well I don’t know yet but what I do know is I want to get the data to use for my query question I want to select everything from my table expenses I’m going to start with the first row and I’m going to repeat all of this while there is a next row in my database if there’s not another row in my database stop if there is a row keep repeating every time my Loop runs I’m taking the five values from the five columns in the current row I’m going to insert that row into my object table remember table is a q table widget and I’m going to insert the current row that I’m on I then go forward and I set every col column in my table to the items that I got earlier those values we end with increasing our row we’re pretty much done with our load method I’m going to go up here into our init I’m going to say here I want this to automatically call load table method every time we boot up because we will always want to load in the database so I can insert that right there self load table let’s run our app now we won’t see anything because currently we don’t have anything in our database great our app still works airfree which means we are ready to go to the next video in the next video I will walk us through how we can add expenses to our database I’ll see you in our next [Music] lesson [Music] we did a lot in our last video and I hope you took some time to read through your notes and review the previous lesson as we introduced a lot more advanced concepts as well as introducing SQL and our databases to our project in the last video you created a database as well as creating a method for loading in our existing database in this video we want to be able to add items to this newly created database wow I’m saying the word database quite a lot let’s go down to our load table method and right after it we can create our add expense method right here the first thing that’s going to happen in in ad expense is we want to retrieve all our input field data let me show you what I mean I’m going to put pass here for now let’s run our code here’s our app let’s say we have a date of today is the 8th 23 I have a category an amount so 25 description uh food category oh I don’t have a drop down box yet I have it but it’s not dropping down let’s address that too but all this information right here I want to capture it it’s like taking a picture I want to capture it and I want to store it in variables remember that let’s go and address this drop down box quickly going up our code where did we we can jump in right here actually so here we create the dropdown let’s jump in here here let’s say self. dropdown let’s say add items add items takes a list just like the horizontal header labels what do we want the items in the drop-down list to say well I want them to be our categories so pretend they are categories you could spend money on food Transportation uh rent shopping entertainment uh let’s say bills and finally other so all of these are options that you can select from the box all right that should take care of that issue let’s do a double check click oh yeah okay great so all this data here we want to capture this returning to our ad expense method now what we can do here is we can create four variables all the information we want to capture I know that I want to capture a date I have a category I have an amount and we have a description so these are all local variables I’m not making them properties they’re only inside this method date how do I capture the date well from what we looked at in the lesson when we introduced this topic we can capture the date by taking that date box so self. dat box I can convert the date and I want to turn that to a string what format do I want to format the date too that’s going to be done here in a string
as well I can say 1 2 34 that’s year so if it’s 2023 it will be 2023 then I can do the month then I can do the day that’s how I want this format to look for my category let’s take our dropdown box so self. dropdown remember the method we used in our last project we can say current text to get the text value of a drop down box item amount self. amount we can say text q line edit we use the text method we saw this as well and we can get our self. description that is also a q line in it getting a text value so we have four variables each of these variables holds the value the face value of our items that we’re trying to collect the data from we now want to take this and I want to drop it or put it into my database we need to create a new question for the database a new query for the database let’s say Q SQL query I’m going to prepare to ask it a question this is a SQL statement so our six quotation marks what do we want to prepare to do that’s what this says well I’m I’m going to prepare to insert into my table known as expenses what do I want to insert well I’m going to insert the date I’m going to insert the category I’m going to insert the amount followed by my description each of these that I’m going to insert so these are like the names each of these are going to have corresponding values and these values will be represented by the information that we give it currently we don’t know it but the information we pass to it it’ll have those four values we are preparing to insert into our table this information that will have four values as well we’ve prepared the query let’s now push or send information to our database so I can take my query and I can say add bind value what value do I want want to go into the first slot of the database I want the date you guessed it we can take this now one 2 3 4 next up in the second slot I want the category the third slot amount fourth slot description we now have added these values to a specific column slot in our database I want my query to now execute it has the information it needs I want to send the information off to my database that is what we’re doing with our query once we’ve created that query we captured all this information from our box well I want to now clear those fields to prepare them for the next expense that you might enter right that’s a convenient thing to do for the user let’s clear everything how can we clear everything this is a method we’ve used before in our previous projects everything we do let’s start with our uh drop- down box let’s say dropdown we can reset it using this method Set current index back to zero we can take our amount field and because that’s a q line edit we can say clear we can take our description box and because that is also clear what am I missing well my date now my date originally was like 1 one 000000 let’s say when it clears let’s actually give the current date as the face value of our app that looks way better too so let’s take our date box and let’s set the date of the date box I want to set the date to the current date to do this we are going to import another module into our app this also comes from p qt5 and it comes from a module that you’re quite familiar with let’s say from PI qt5 QT core I want to import a class called Q date this will allow us to get the current date let’s return to where we were inside our set date method what do I want to set the date to well I’m going to take my Q date that’s a class but I’m not giving it any arguments I just want to link it I want to link it to something called current date just like that that is going to change the value of that date box to the date today and as of today it is July 8th amazing the last thing we want to do what do you think we want to do after we add an expense the last line of code well I have new information so I want to now look load this new database I’m going to call the method we first made load table as I have new information in our database great I’m excited let’s give our app a run at this point we have the ability to add information to this table before running the app break down and pause what is happening here let me go through and translate this when we click the add expense button so we need an event first but when we do click it we capture all the data from the input boxes at the top of our code we capture a date we capture the current text the amount and the description then I’m preparing to ask my database a question or preparing a query what am I preparing to do well I’m preparing to insert something into my table that we named expenses I’m going to insert in the format date category amount description each of these will have a value they have four values because I have four columns in our database then in my query in the order that we said we’re going to give it the information we are adding a binding value that’s going to bind with that current query once we add all the values we want to execute and send the query off to our database we’ve added something to this database it’s now time to prepare our app for the next input so we want to reset everything finally ending with loading our new database into our table in order to get this to work let’s link this to our ad button where did we create our ad button up top let’s go up top to where we made the ad button and right after here we could just say Okay self. add button. clicked when that’s clicked we want to connect to our new method add expense all right time to run the code let’s give it a run things are starting off let’s start things off with our date today so let’s say 8723 today food amount 10 description tacos add look at that we have added something into a database and taken that database and loaded it into our app let’s go for another one this time let’s say rent let’s say someone’s rent is 500 let’s say description landlord add ooh we have the ability to add things this is great we can say night out when did we do this night out let’s say one amazing we have almost full functionality of our app the last things we need to do is program our delete button and any designs we want to do well done I hope you’re starting to see the gears turn and how we can use SQL to enhance our applications it’s a way for us to store data within a database in pull it as we need it I’ll see you guys in our next lesson where we will introduce the delete expense [Music] method here you are in the final stages of your app and very well done because you’ve been introduced to a big new topic topic and you’ve only just scratched the surface what was that new topic that we’ve learned in this project well SQL the structured query language that we use while interacting with databases and you’ve gotten it down so far let’s finalize this app what’s left to do well our delete function our delete an expense what do we need to do to achieve this well in order we want to get the row that we clicked on from our table remember this method we’ve used this before so whatever row we click on I want to capture that and I do want to check I want to run a quick check and I want to check to make sure that I indeed chose a row within that database if I did I can create a variable using the ID of the row that I selected we can generate a question popup and we can ask the user if they want to delete yes or no remember the Q message box well we’re going to use that here along with the question method if I choose yes from my popup box I can prepare a query and I want to SQL syntax delete from table where the ID I collected is equal to the value we can then load in our new table using the load method that we previously made if we look at a little bit of the code from our delete method you can see in the first part I am creating a variable and the value of this variable is whatever row we click on I am capturing that from whatever row I click on I want to get the ID from that row so I’m saying my ID this new variable is equal to my expense table item the selected row column zero because I know that no matter what every Row in the First Column which is column zero that is actually holding the ID of that row so I am selecting so if I click on row five I want to go to row five and get the information that’s in the First Column and convert that to text that’s our ID based on that ID I’ll now create a new query and I’ll say hey prepare to execute this query all right I want to send my message and I want to execute the query so my expense ID is right here that’s our question it’s going to to remove that row and load in our new database right this prepare query where it’s preparing let’s translate that it literally says delete from my table named expenses but only where the ID matches the one I give you here that is how we could program out our delete method if you want to try and implement this yourself jump on over to vs code and I’m I’m about to head over there myself I’ll see you over in vs code let’s finish off our [Music] app you’re closing in on the final details of your project the last thing we should be doing is adding our delete expense method we have our functionality down we want to have the ability to remove something from our database from our app table let’s head down to our class and after our ad expense method this is where we focused our endeavors last lesson let’s create right here our closing method this will be our delete expense method let’s clean this up a bit so I’m going to give some space what do we want to happen how can we delete something well what I want to try to do is I’m going to click a row in my database and I want to capture whatever row I click I want to delete that row whatever row we click on after I click my delete button we have within our UI design so for whichever row I click on I want to capture the ID that’s linked to that row and I want to delete it from my app screen as well as my database let’s start with I want to capture the row that I click on let’s create a variable called like uh selected row this is equal to my table do you remember how do we get the value of the row we clicked on we’ve done this before actually and we did this in our last project I’m going to say current row so the value of this variable is one of the rows that I click on in my table first things first I need to make sure that my database is not empty because if I click into an empty table if there’s no database or there’s no rows I should not be able to delete anything so I need to anticipate that someone might try to do that let’s make sure that if the selected row is equal to -1 so that means you actually did not choose a row from the table you clicking the delete button but you did not click a row yet I want to alert the user to a problem an error what is the best practice for us to alert the user let’s give them a friendly message box and let’s just give them a nice warning and say hey something’s going on here and you might want to address that so that’s a part of myself and I’m going to say no expense chosen you are the chosen one you didn’t choose one so we can say that and I’m just going to say hey please choose an expense to delete that looks nice exclamation point we can simply then just return that that’s going back to the user nothing else is going to happen we now have checked and warned the user that they need to choose a row if they’ve chosen a row we want to capture the ID from that row so specifically the text value of that ID let’s create a local variable and previously we have one called expense ID I can use that here because this is within my method expense ID is going to be a number now the number is going to be something from my table and it will be one of the items in our table what item do I want from the table well I want to get it from the row that I’ve clicked on and I want it to be from column one which is column zero remember in our database the First Column is our ID that’s what I’m capturing I’m getting the ID from our database from the table specifically everything in the table is a text object so I’m just going to say text here this whole item is an ID text value but we’re converting it to an integer which is good I have an ID let’s double check and make sure that that user really wants to delete it CU if they don’t then okay let’s give them a second chance let’s create and let’s say something like confirm confirm is going to be also a friendly message but this is going to be more like a question because I want to make sure and I say okay are you sure that you want to delete this so we can say are you sure question what do we want to say then we can say delete then we need to give them two options and it’s telling me to give them two butt buttons now these are going to be our Q message buttons so we can say the options are going to be Q messagebox do it’s going to be yes or no I can say that like that so I’m going to confirm and this little question box which we’ve looked at before is going to pop up and it’s going to ask the user if they want to delete an expense the user will then be given two options from which they must choose choose yes or no if our answer so if what we get back from confirm is equal to no what do we want to do well I just want the program to end I don’t I don’t want to delete anything here’s a popup box if the confirmation is no just exit out of this method I’m done using it I don’t want to do anything I don’t want to delete that item but if this condition is not true it means we do want to delete an item and we clicked yes what do we need to do to remove an item from a database well it’s kind of the same question what do you need to do to create a database to add an item to delete an item we need to ask a question I’m going to prepare a query the query that I’m going to prepare is I’m going to take this query and I’m going to prepare something what SQL syntax do we want to use well I want to delete from my table called expenses everywhere where the ID is equal to the bind value I give it what’s the bind value well the bind value is going to be the expense ID this expense ID that we got from the row we clicked on is going to be where the ID matches that so delete from our table everywhere where the ID is equal to the row we clicked on that’s us using the ad bind value again finally let’s execute our query it’s time to run it now that we have new data let’s load our new table the updated version of our table into our application this pretty much wraps it up the final step that I’m going to put on here before a quick test going up to our buttons we just need to connect self. delete button doclick do connect we can link our delete expense method are you ready for this let’s see if our expense tracker is ready to go running our app let’s choose so you can see here my app’s loaded and it’s loaded in our saved database that’s the point of a database we can save information every time the app fires up it’s loading that in now let’s say I want to delete this rent that was an error so I’m going to click I could click anywhere in this row I’m capturing the current row delete expense do I want to delete it no okay so nothing happened entertainment delete yes look tacos that was a mistake yes you can see our database working look at that amazing well done to everyone I’m so happy with how far we’ve come and how many projects we’ve been working through you started off with not knowing what this new framework was but now you’ve come so far and you’ve learned how we can use this framework pqt to build out window applications in Python and we’re not done yet there’s more projects to come and more tools that you’re going to learn I will see you in our next [Music] video [Music] you’ve just finalized your expense tracking app we’re at a later stage in this course and you may be wondering okay how can I start to implement a bit more styling into my apps this could be changing colors or adding boxes anything like that in the next few minutes you’re going to learn how we can style our pqt apps with CSS what is CSS you may have seen this term before you may have actually used CSS as well let’s take a look now CSS is used to style websites specifically it’s used with HTML and JavaScript and it can be used with other languages and this also includes python how does CSS work well our casc G styling sheet that’s our abbreviation CSS we use it to Target specific elements in our code so for example if you have a website that has H1 elements these H1s are the big text the headers I want to Target all the H1 elements and I want to give them the font size of 32 and the font family Gothic so I can use these parent elements to Target specific objects on my page or in our app and apply filters or apply stylings to them in CSS we have our main elements which are like your H1 tags any of your header tags your paragraph tags anything like that you can also narrow it down so if you created a class in HTML you can Target the class by using the dot with your class name now keep in mind this only works for HTML this class structure as in Python we have something different and finally you could style it by ID and ID is very specific so I’ve actually put this in the order it takes precedence with our least important in between and the most important we can use our styling CSS by targeting our element followed by a set of curly braces inside the curly braces we put the font Styles we want to apply to that element what would this look like in pi QT well it’s actually going to look very similar we can style the same way in pqt we just need to use the set style sheet method inside here the only difference is all of our styling is actually a string and you can see I’ve specified that by using a multi-line comment or a multi-line string with three quotes in the beginning and at the end what elements are we trying to Target well remember with CSS we are targeting the parent elements originally these were our main elements and classes well we can Target that with pqt and python too you can see here I want to apply a background color to my entire app my finance class this will apply a solid background color to everything everything that is a q label a q line edit or a q push button they are going to have these Styles then my Q Tree View could have this style now we haven’t talked about Q Tre view but don’t worry I’m just including classes here as examples but we will see these at a later stage in our course let’s jump back into vs code and let’s finalize and style our app I’ll see you guys in the next video [Music] video it’s time to add some styling to our application our current application is looking like this let’s take a look at what we’re actually going to achieve in this video I want to take our application from this all the way to something that looks like this now you can use your own colors of course this is just going to be what I’m aiming for and we’re going to do a little bit more than just CSS I have some bonus surprises we haven’t talked about in order to tweak our app but don’t worry as we go through I will break it down and give you a good explanation all right let’s move these off and and jump into our code at the top of our code uh I’m going to go in here let’s just import QT the first thing I noticed was when our app started we don’t actually have the initial date set so let’s take our date box and let’s call Q date we’ve actually done this before and we can link our current date method to our class Q date now when the app starts it’s going to have today’s date on it okay next up I want to go down here to my table I want to design my table a little bit more there’s currently a few things I don’t like going on let’s bring our app back up in our app I don’t want to see this bar at the bottom I don’t want to move the table I want it to be hardcoded so how can I prevent that we are going to take a look at that and then another thing I want to do for example if I add this expense I want it to go in descending order so at the top I have my newest entry my newest expense and it goes down to my oldest expense let’s try to implement those two functionalities the first functionality here I’m going to take my table I’m going to say self. table and I’m going to take horizontal header I want to apply a method and I’m going to say set section resize mode this is going to allow our table to be hardcoded and take away that scrolling bar so it’s going to look nicer and more clean within here we need to stretch the header I need to stretch the table so to stretch the header I’m going to use something called Q header view we haven’t imported this yet but it does have a method called called stretch let’s go up I’m going to throw in here and I’m going to say Q header view as a q widget there we go so this is going to stretch our header across our entire table widget brilliant the last little tweak I want to do to my table is I want to sort them so everything is in descending order let’s take our table and thankfully pqt has an awesome method method called sort by column and inside sort by column it’s going to take the column we want to sort so if you remember in our app the First Column is actually our ID I want to sort the second column this is at position one so inside here I’m going to put one as I want to sort by column one and then my sort order I’m going to use QT and I’m going to say descending order now that we’ve styled that it’s now time to add in some of our CSS let’s clean this up I’m going to add in my CSS before we add everything to our design so let’s say self. set style sheet inside here remember we need our string 1 2 3 4 5 6 then we can add in our CSS what do we want to change well I want to change a few things in order to change my entire app we need to remember that our entire app is actually a q wiget so I want to affect that parent element of Q widget returning to set stylesheet let’s say okay so Q widget I would like to apply some styles to I’m going to give them a background color and the background color I want to be I have picked out is this great we have that color what else do we want to add in our Q widget well I have my Q widget let’s say we want to affect our Q label we could affect our q line edit if we want to affect more than one element with the same styling I can put a comma so in this line I’ll be affecting any q line edits we have any Q combo box Q date edit as well as any Q push buttons we can have our Q table widget Q push button and then the last one we are going to apply a state so for example with CSS I could apply a hover state or other types and to do this I can use a semicolon and I’m going to say okay when the Q push button buttons are hovered over with our Mouse then these Styles will be applied I’m going to go through and I’ve already created some styling that I’m going to add in here let’s see what we’re going to add my stylings look all ready to go let’s walk through and see what I’ve done here so I’ve taken my Q label and my Q labels are going to have a darker font to them and I’m setting their font size anything that’s text Q label all of my Q line edits combo boxes in the date edit box they are going to have a background color of this the text within those boxes will be this dark gray and I’m giving them all a border around the perimeter of that object with a little padding my table widget will be the same color as my overall background and it will have a border so we will be able to see the difference between the two in between each row and column I’m going to have white or like this grayish color I’m applying my Q push buttons will be green with white text no border then when we hover over the button the color is going to change ever so slightly so a little bit darker wow look at all the styling so we can do that within one method self. set style sheet this looks great let’s try running our app and seeing our end result is it what we’re aiming for amazing it is exactly what I was going for and you can see as I hover over these buttons they’re changing color all of our items match the background color and I’m hoping that you used some of your own colors too let’s add our expense everything is working how we want it to delete look at that even our Q message boxes are styled to what we set this looks amazing incredible job have a play around with CSS and do a little bit more research because in our next app you’re also going to use CSS to do some styling I’ll see you in the next video for an introduction into our next project [Music] are you guys ready for our next project cuz I certainly am we are about to dive in and create an interest rate calculator application in this application you will be using everything you’ve learned so far but in order to create this we need a way to visualize data in Python we will introduce a library used for data visualization in this project let’s break it down here is an initial overview of our app take a look at what we see going on and what this app can really do we have the ability to enter an interest rate the initial investment M or the amount of money that we want to put in and the number of years we want to invest for you can see up here here is the interest rate here is the initial investment and then here is the number of years we want to invest for you can also see that I have a little box here for dark mode which is a way that we can style our application even more we can create a chart we are going to display in a table or some type of view all of our interest rates calculated and then finally I want to have the ability to save so when we click this button I want to save our chart but then I also want to save our table as a CSV file what widgets do you see on the screen right here well we know all these except Q tree view this is going to be a new widget a new class which allows us to have it’s almost like a q list widget but we have two lists going on we have two columns we have a year and we have a total then we do need something for our chart but just for the initial setup and design for now let’s just use Q Lael very similar to what we did in our image editor app are you thinking about your layouts and how you’re going to design this app a lot of things are happening here what makes sense to you what is the easiest way we could design this are we going to have a master row or a master column and what will be inside our Master layout what I’ve come up with is I’ve said that I could have two rows because at the top of our app we have a lot going on up here so this could be held in its own row then I could structure in a second row and within the second row I can have two columns My First Column is going to hold my Q Tree View along with our buttons and my second column is just going to hold the area with the chart this for now can be our Q label our design will have two rows row two will have two columns and together Row one and row two these will be held in our Master layout that Master layout we can drop that into a column start thinking about this because you’re about to head off and design the app on your own So based on your experience with pi QT and everything you already know how can we set up this app to the best of our ability I’ll see you guys guys in the next video where together we will prepare the initial layout and design of our [Music] app all right here we are in the initial setup for our interest rate calculator app you know what to do here building on all the knowledge we have been learning how can we set up our initial project let’s kick things off with our Imports what do we need from PI qt5 we are going to do our QT widgets import everything we want so Q application Q widget what else are we going to be needing for our application well we need our Q labels we need our Q push buttons let’s get our layouts in there before I forget them so QV box layout Q hbox layout we will use Q Tree View that’s the new widget item we have our q line edits so I can say q line edit and finally here I’m going to talk about something briefly called Q main window let’s put that in as well and this will allow us to create a window very similar to what the Q widget does but it allows us to inherit it a little bit differently great I am then going to go and I’m going to import something else so I’m going to go to qtgui I would like to import Q standard item model this is what will allow us to to build out and add elements to our Q Tree View itself great we want to create a class-based application so I’m going to create one called finance app and instead of inheriting Q widget this time I’m going to inherit the main window itself so let’s say Q main window you’ve seen how we can inherit Q Widget the same thing’s going to be done here for main window and it’s it’s going to act very similarly let’s create our Constructor what do we want to run when the app first starts well everything actually up top here I can inherit and so let’s say our super function I want to inherit everything from our finance app and I’m just going to say in it just like that so I’m inheriting I’m initializing this as a super class as well as activating the main M Window what this translates to is I am activating my super class Q main window and I’m giving my super class my class that we just designed this is how we set up the inheritance for Cain window what do we want to create well I can set my window title now we know that what do you want to call it interest interest me 2.0 I don’t know that’s kind of cool okay let’s give it a resize what would the width and height of the app like to be let’s say to kick things off 800600 all righty because I’m inheriting Q main window I don’t have a Q widget yet so we can actually make that locally inside our Constructor method so let’s say our main window and let’s say that’s equal to our Q widget like so I don’t need self because it’s not going to need that it’s you used and constructed right here let’s create all the objects we want to see on the screen I’m looking if I run my class what objects do we want well if I run this app I want three text labels at the top and three q line edits that’s going to be in the first row I want my treeview two push buttons and then for now A Q label let’s start off just in the first row so interest rate initial investment let’s say rates text I have that I’m going to say rates input that’s the input let’s create one for uh initial text we’ll create one for initial input we can create one for years so years text and we can say years input now that I have those all sorted I can just go through and I know these are going to be Q label so I’ll say Q label take that two times we have two more and then our next one we know is going to be a q line edit so let’s get this all prepared for us all righty in the first Q Lael rate text we can just say like interest rate this is going to be in a percentage looking good so our first one is interest rate then we have our initial investment our final one is going to be years to invest so our row I have all those objects this is going to now bring me into let’s say creation of our tree view so how do we use Tree View and how do we get items to it what I need to do is I’m going to create something like a model and this model is ultimately going to hold my tree View and it’s going to allow me to add items to this model self. model is an object from this Nifty class that we’ve imported from our qtgui I can then create my treeview let’s say treeview is equal to Q treeview it doesn’t take any arguments right now I can take my treeview so self. treeview and I would like to set the model to become my my model great look at that all come together we have our starting row I have created my Q Tree View and I’m preparing it to accept items within the tree View and we are setting our model then our last three things are I want a few buttons so I’m going to start off by creating my buttons and say let’s say I have a cal button and let’s also say I have a clear button our C button can say calculate and our clear button can say clear then I’m going to create a figure now in the end ultimately this is going to hold my chart but I haven’t introduced data visualization yet or our new module that we will use for this so for now I’m just going to say Q Lael and I can just say uh chart will be here soon that’s just like placeholder text next up we have all the objects what should we be going into we should be going into our design right we can take our design for our app so let’s create that I’m going to create my master layout I’m inside in it so I can use self like that I know that I want it to be in a column I know that I’m going to have Row one and that is our c and we also know that we also have row two that can be our Q as well now within row2 there will also be two columns if I created those now I can just say column one that’s my QV and column two is also our QV box let’s start off with Row one so I can take my Row one and let’s add all of our widgets to them so I’m going to actually copy this I know I’ll be needing it the first element we want is going to be our rate text our rate input let me get the other four added we have everything added to the first row I can carry on now to row two now within row two I have columns so let’s let’s begin with those columns actually I’m going to take column one we want a lot of things in here initially at the top I I want my treeview so I can add in my treeview itself directly under treeview we would like our calculate button bringing us to directly under our calculate button we can just insert that clear button let’s take a look at what we want the app to look like as well one more time I have put everything in the column I now just need to add my Q label to my second column before we can add it into our row taking column two adding the widget what widget do we want to add here well I want my figure to be here eventually which will be a chart great we have our two columns let’s take row two and I would like to add layout Row one and row two I can take my master layout now we can add layout to that and at top we want to say Row one and row two I can see a little mistake here I threw off right here I’m adding to my row row one and two this should actually be column one in column two set we can take our main window we can set that layout and we can say selfmaster layout a great everything’s set up and it’s ready for running but let’s come outside of our class real quick cuz we don’t have anything so if name is equal to main then let’s create our app object and say Q application we can create an object and say well let’s say my app is equal to our finance app let’s say mya. show and then let’s take our app and let’s execute our app before we run our app we’ve set layout now I’m inheriting Q main window and we’ve seen this before with our Q widget because we’re inheriting it I want to set like a central window so I can say set Central widget what do I want the main widget to be well my main window that’s my main widget so I’m going to set that here in line 62 that’s the last and final part of using our design with Q main window when we run the application we see everything come to life now this looks almost ready to go and ready for the next stage but this tree view is huge ideally I want these to be swapped so chart will be here soon this should take up the most space how can we do that we’ve done this before remember I need to set the width and the percentage of my columns Let Me Close Our application let’s find right right here let’s give this a try so I’m going to say column 1 is going to occupy 20% column two is going to occupy 80% of the screen looking much better this is how I want the app to look we are ready to go in the next lesson we are going to convert your data and get it into our tree View and calculate our interest rate starting to visualize our data before we take the data we’ve created and generate a chart or a plot with that I’ll see you guys in our next [Music] lesson [Music] great we have our app set up in the initial design ready to go now we need to talk about how we are going to calculate our interest and how we can use what we calculate to put into our tree View and into our chart what are the step steps we need to do in order to calculate our interest well if we take a look here I want to add the interest calculation to the Q Tre so we are going to create a method and this method is going to do all of the following it’s going to convert all our input fields to numbers so all these guys will be converted to numbers and we do want to try to catch any error so think about that what error could occur in this program if we try to convert these fields to numbers what if the user enters something that’s not a number we want to catch that and alert the user to this so think about Q message box once we’ve converted all of our input fields to numbers we want to then create a list for every year I want to multiply the total investment by the interest rate our calculation is right here I can create a treeview and each item in here is going to be something called a qard item we can import this into our project this is going to take a single item that we want to add to a treeview we can add our item year and item total to our treeview as a list so think about how can we do that as a list finally once we have data in our box I want a save button to appear on my screen initially when the app starts we should not have a save button because you can’t save if we don’t have any information so pause the video read through each of these steps what would you need to do in order to achieve or to solve each of these steps here I am using to calculate the interest the value that we enter into those fields so this interest rate I could store that in a variable and use that and then this initial investment that’s like my total I could store that in some variable as well this calculation is the equivalent to the output of our interest rate the input that we entered in number of years you can see that that’s displayed in the First Column versus the second column let’s take a look at converting all of our input fields to numbers and how we could catch any errors with that we have our try and accept statements what do we want to try to do we are creating these local variables in the function and we’re trying to convert all of our initial properties to a number number now remember a q line edit we can get the text value of a q line edit by using the text method and linking it to our qine edit object now that I have the text value I want to try to convert that to a decimal a float number we try to take our values we entered and we convert them as we need them I’m going to try and catch any errors specifically the errors that I want to look out for are value errors so if the user enters something that is not a number I want to catch that as a value a and to alert the user we can use our Nifty Q message box and just give the user a warning and say hey um you need to enter a number please try again we’ve now converted all of our input fields to numbers or we’ve caught the errors to do so what comes next well we need to calculate our interest we had a local variable called initial investment but I don’t want to change that variable that value um I do want to create that so I can change it so I’m making a variable total and whatever our initial investment was that is now the value to this variable total try and break down what’s happening here as I go through where do these correspond to what you see in your app for every year in the number of years I entered which is essentially this I’m going to take my initial investment my total every year I want to add the previous total and I want to times it by the interest rate so so every time this runs this is going to start with the first initial investment multiplied by the interest rate but then the second year comes and you can actually see here in my treeview that the numbers changing because I’m earning interest off my initial interest and investment so as the years go on it’s actually updating that’s what’s happening here I can create an object item year and item total and remember to add these to our Q Tree View I’m going to use that new class Q standard item so I’m adding a year and I’m adding a total I can then append a row this method I’m using with Q Tre view specifically to append a row which means a row is going to have more than just one item in there remember that we said we need to add a list my item year is column one my item total is column two now this is kind of strange what’s going on here well a string format specifier this allows us to format all of our floating points with two decimal places this specific syntax is telling us the number that should be formatted or how many digits afterwards I want two digit digits after the number and you can see here 76 cents or 42 cents that’s what we are formatting where is everything coming from in the app well let’s keep with our color coordination our goal now is to head back into vs code I want to be able to program a calculate interest method that when we call this method it’s going to insert all of our data in into this Q Tree View as an added bonus try to create a reset method when I click the reset button I want all the contents in my treeview my interest rate investment in years I want those to be reset how can you do that using the clear method I’ll see you guys over in our next lesson [Music] it’s now time to calculate our interest rate and display that in our tree view let’s go down and let’s create a new method after our Constructor right here I’m going to make a method and I can call this calc interest giving itself and in the beginning I’m going to create a variable called initial investment I know that it’s going to have a value but currently it’s none we want to try to do a few things I want to take all of our inputs from the top of our app so our initial investment the interest rate and a number of years and I want to convert those to numbers so we need to check and try to do that let’s create a try statement and let’s say okay uh interest rate we have that I am going to get my initial investment and then we’re going to have the number of years for interest rate let’s convert a float and we want to get our uh input something of input text uh rate input we created that initially that’s our q line edit and we can get the text value of a q line edit by using the text method we can do the same thing for our initial investment this is called initial input get the text for number of years well calculating the interest of number of years is usually done in int so whole numbers and so let’s just convert that to an INT get the text awesome if this doesn’t work let’s throw an exception so a value error so you must enter a number you can’t enter a space a letter anything like that or it’s not going to work if this occurs let’s give the user a nice warning so I can do that by using our Q message box warning is it parent is myself we can say Okay error and let’s just say invalid input enter a number like so looks great if that’s the case you can return that we now at this point have three number values that we want to use to calculate our interest do you remember the equation we’re looking for let’s try this calculation I’m going to create a new variable because I don’t want to edit the actual value of my initial investment but I am going to use that as a starting point what I can say here is I can say for every year in the range of one because if I have an investment the minimum is one year and my variable number of years plus one so for every year if I have my investment for 10 years this Loop is going to repeat 10 times every time it repeats I’m going to take my total which the first time this runs that is the initial investment and I would like to add the total but I’m going to multiply that by my interest rate divided by 100 great we have this I can take my item year now in my item year I would like to add an item to my treeview in order to do this at the top I imported a class called Q standard item this allows us to add an item to our treeview which if we go up a little bit we have right here standard item model I’m going to add a standard item to this model model going back what do we want to add as the item year Well I want to add my current index so the year that’s like for I for every year I want to add that current Year to my treeview then I want to have the total how much did I earn that year essentially inside here we want to put and format our code so I can do something a little bit strange here let’s give ourselves some curly braces and let’s go to the end of our total and I want to cut off the last two decimals so I can say to F I can then format my total which we initially collected right here that’s being formatted to only secure two decimal points what we want to do is I want to take my model that we created really our model is that treeview the fancy method append row allows me to append a list in this list in the First Column I want it to be item year and then I want it to be item total just like that this pretty much works as a bonus I asked you to actually Implement a reset method so very quickly I’m going to do that let’s call a method reset and say self for this we didn’t really have to do too much what do you want to reset well we’re going to reset our rate input we’re going to reset our initial input and then finally we’re going to reset our years input we can just use clear because each of those is a q line edit what is left to do well let’s go up here now we just need to go at the bottom of our init and we need to take our buttons so I have a cal button and we have a clear button and we want to say when the clear button is clicked we want to connect to our reset method when the Cal button is clicked we can connect to well you guessed it we want to connect to the Cal interest method all right let’s run it let’s see if we can take our data calculate the interest and display that into our Q3 view let’s say we have an interest rate of 8% the initial investment can be 10,000 and years to invest 15 years calculate look at that we did that I’m going to make this a bit wider okay but this treeview is working great if I click clear you can see see that we’ve cleared all of our inputs let’s just end this on a high note and add the final two touches let’s make the tree view a little bit wider and then also let’s clear the tree view going up here let’s just change this to a 30% width and a 70% width going down to our reset let’s take our model let’s say self do model clear try it one more time again 8% let’s say say 10,000 let’s say 15 years calculate look at that clear everything is cleared we are looking great we are about to head over into our next lesson and we are going to introduce the new topic of data visualization in Python this can become incredibly useful in your python journey and your career as a data analyst or a python developer I’ll see you in our next lesson for the introduction of math plot [Music] lip it’s time to get our hands dirty and jump into how can we take all of our data in the tree View and how can we use that to generate or create a chart to do this we are going to use a powerful python Library called matplot lib let’s jump in and explore how this new module works and how we can use this to our advantage in order to import map plot lib I’m going to do two things number one I can import map plot lib and I’m going to give it a nickname I’m going to reference it as PLT and this is an extremely popular naming convention that you will see in other code that uses this module I’m giving it a nickname PLT which is like plot that I can use at later stages in my code now Matt plot lib and pqt actually use different backends so we need a way for them to communicate and talk to to each other because we are using M plot lib with pqt we are going to import one additional class for our use I’m going to import from the backend modules of map plot lip I’m going to import a class called Figure canvas QT and this is a really long name so it’s popular to see also renaming that class to figure canvas so I’m importing this class and I’m renaming that as figure canvas this acts as a bridge and it allows us to create charts or canvas objects and that’s acts as a container so it allows us to wrap our chart in a canvas and this allows us then to take this wrapped canvas and put it into an app like pqt this is why we use this class figure canvas take a look pause have a read through I’m using the back end of matplot lib to wrap my chart to use in pqt let’s take a look at some popular methods that we will use for data visualization anytime we’re working with this module map plot lib this is one of our most powerful Tools in Python when it comes to data visualization you will most likely see two popular librar while working with python one being matplot lib and for its Simplicity in used in scientific studies but two another popular module that you could use is called plotly in this course we are just going to jump in here and use matplot lib as it’s easier to start and easier to understand you can hit the ground running with your data visualiz Iz ation we can use this to create simple plots line graphs scatter graphs anything like that what we are focusing on in this specific project is going to be a line graft for us to see how much interest we’re earning screenshot or write this down take notes anytime you see a table with me explaining these new methods it means you’re going to be using them more than just once it’s a good idea to write them down to understand this new library as a whole the first method we have is called subplots this can generate one or more plots in a single figure so imagine for example here is one plot what if I want four plots well that’s one figure now I break it into four plots I can use this method to do that we have the plot method and this will try to plot the data that we give this method so this method does take an argument it takes the data you want to see and it’s going to try to plot that you’ve seen this method with pqt it’s also a part of Matt plot lip once we have this plot we want to show this plot for readability for anyone using your app it’s good to give your app names and more specifically your chart your x axis your y axis in the overall title of this chart the xaxis it could be the length of time years and your y AIS could be how much money you’re earning the title of your chart could be something like interest rate we have a method called Figure and we use this to generate a new figure or if we already have a figure I can get a reference from that but for this app and to start off we are specifically focused on creating a new figure and finally we are going to see the draw method and this is used to redraw a figure and update its contents think about that let’s take a look at how we can now set up a plot if you remember when you initially designed your app you initially designed your app in the chart portion of it as a q label we said in our code self. figure equals Q Lael well now it’s time to change that we are going to change it from Q Lael to say plot remember we imported map plot lib and we’re going to call the figure method creating a new figure now that I have a figure I’m going to be working with this figure in pi QT so I need to give it to the class that we imported this figure canvas class allows us to work with Matt plot lib and Pi QT together we are giving it the plot that we created then we are just adding it to our row so you can do this entirely on your own it’s just updating and tweaking a few parts of your design your initial layout returning to our method now we have one method for calculating interest in our application our code for generating this plot is going to go within that method now these steps are not in any order at all can you reorganize them and put them in the order that they should be in based on the way our code is running if I take them let’s reorganize them okay you can see all the methods that I previously introduced I’m using here to generate my plot my chart we are creating a new plot and I’m making a list of years based on the input that was collected from our q line edit all right I’m using a list it’s going to range a certain amount of times we’re obviously going to start with at least one year and then we want to go for however many years we entered into our q line edit I’m adding one because python starts on zero remember that we are creating a list of Interest over the years and what you see here is called list comprehension this is a slightly more advanced python Topic in your python Journey you may have used list comprehensions before or seen them around but don’t worry in the next few slides I will break down this specific example for you the final three points we have are we want to try to plot the data and then that data we plot it’s going to make a chart I want to give all the titles to my xaxis my y AIS and just the chart in general our chart is 100% set up I now want to update my chart so we can see it on the screen another thing you see here is ax you could call this anything but you will see as a popular naming convention the variable ax is used when working with matplot lip what is list comprehension now when I break that down what are we trying to achieve in this list example well let’s break it down what I want to do is I have a list and this list is called totals and I want to add a certain number of elements to this list if I’m going to invest money for 10 years I want there to be 10 different elements in my list so in my example I have said I’m going to invest for 15 years so I’m going to repeat something 15 times every single time I repeat this Loop I’m taking my list and I’m appending something to it I’m taking my initial investment and I’m multiplying it by the interest rate in the current year this is like how much money you would earn after a year for example if I Chang these numbers and I said 10,000 10% interest rate I would be appending the number 11,000 to my list the first time that ran the next time this ran what do you think we would be having well it’s not going to be 11,000 anymore can we use our input values instead instead of hardcoding these numbers we can remember that we collected the value of everything we entered into the inputs and we converted those to numbers so we already have those as variables let’s now use them initial investment interest rate that’s what we did we went from this we changed it down to this now I’m not hardcoding anymore I’m using the value of of my variables which could be changing it’s whatever the user enters into the app let’s take this one step further we now have this how can I combine these three lines of code into one this is list comprehension now that you understand what we’re trying to achieve in this list let’s combine them in our code you can see that I’m defining a new list called totals you can see my square brackets then the calculation for each element in the list and this just takes our initial investment in the interest rate and it’s squaring it based on the year so all in all this is just one number this is like 11,000 from my previous example then the comprehension is I’m putting a for Loop in my list and I want to repeat the number number of years that we entered in our input remember we stored that in a list years that we created previously let me return now to what we initially saw this was the setup for our code can you implement this let’s try it I want to start to see some charts on our screen let’s head over to VSS code and I will see you guys in the next lesson it’s time to implement map plot lib [Music] you now have a basic introduction to how we can take data and create visual visualizations using this data we have that Library called matplot lib or matplot Library let’s get that into our code at the top we need to get the standard pip plot library or module from matplot lib let’s import matplot lib but the ply plot as PLT that’s the popular naming convention then remember that map PL lib in pi QT have two different backends so there’s a special import we can use when working with matplot lib in pqt we can say here from matplot li. backends backend qt5 a what I want to say here is I want to import specifically figure canvas QT and I can nickname that now as figure canvas so PLT and figure canvas are already popular naming conventions you may see in other code when working with map plot lib with pqt okay I’m going to Mark those we now have this new module imported for our data visualization I want to go down remember that our app has this Q label so I have a property called self. figure but initially I set this to a q Lael we now want to redo that the value of Q Lael is going to be a figure of some sort now this figure I need to create and convert to a canvas remember that a canvas is like a giant container that’s going to hold my figure in pi QT so this canvas is going to be an object actually and we’re going to use that class we imported this is like a wrapper and it’s going to wrap my figure in my canvas we can then just go down and we have actually added in here already I have taken my column I’ve added my figure let’s just change where it says figure let’s now add our canvas marking that off we’ve created this new mat plot lib figure wrapped it in a canvas for pi QT and then set the canvas to our column two okay the design part is done we now need to take that data and convert that and display this in our chart going down here we’re going to do this inside our calc interest method the first part of what we did here was we got our data we converted it and calculated the interest to display inside our Q Tree View what I want to do here is I want to like update my chart with our data this can be done so the first thing I want to do is I want to take my figure and I want to clear it off from any old data we don’t want that then by popular name I’m going to say ax this is like our axis I’m going to create a plot and I’m I’m going to say figure. subplots method this will allow us to generate a chart and if we wanted to I could create one figure or I could have four figures within one so I’ve generated a chart that’s now called ax for all intents and purposes let’s create a list of years so this is potentially going to be the x axis on my chart because as the years go on my interest goes up so my years is going to be a list how many elements do I want in this new list well remember if I enter that I will invest for 10 years I should have 10 elements in this list 1 through 10 So within this list let’s say it’s going to have a range of one all the way to the number of years plus one just like we did up here for our for Loop we have our years I now want to calculate my initial investment for this we are going to do some list comprehension now remember I talked about this in the slides in the lesson this kind of gave you an intro to what list comprehension is and how we can nest in a list to repeat a very similar task so I have a list of totals I’m going to start with calculating the first element so the first element I want to take my initial investment and we’re going to multiply it by our interest rate so that’s going to be 1 plus our interest rate divided by 100 what we want to do is I want to take this and raise it by the year that’s just one element okay all this is working together as one now I want to repeat this for a number of times so I can say here for year in years remember that years is a list we just created so it’s going to Loop for however many years we have in this list every time it’s calculating the interest for the current year and adding it to this list called totals that saves us a lot of code and this is more advanced python that we will see as we progress through our journey next up I have my data that I want to plot so I’m going to take my figure and I’m going to try to plot what do I want to plot well I want to plot the years and I want to plot the totals now that we’ve given some space there let’s take it and let’s give a title so I can use the set title method I can uh use the set X Lael method and we can use the set y label method let’s give a name to everything I’ve now given the names to the Chart the last thing I’m going to do here is I am going to take my canvas and I want to draw on that canvas using that method let’s also go go down here and I’m going to add in two more clears so when we click the reset button I want my figure to also clear I would like the wrapper my canvas to also clear our app is pretty much ready to run let’s go through we cleared any old charts we created a subplot then we generated data so my years is a list my total is all my interest calculated then we set that data to our plot giving it a title an X label a y oh our y label and then we drew on our canvas we can run the app let’s say an interest rate of 10% with a $115,000 investment over 20 years calculate look at that we took our data it’s not only displayed in treeview it’s also displayed in an image a picture this looks incredible our app is almost ready to go I want to have the ability to save this data as a CSV file and this chart as a picture let’s head into the next lesson and let’s talk about how we can save all the data we’ve just generated I’ll see you guys there [Music] we’ve come so far we have implemented not only a new tree view which is like a table but we’ve also implemented a chart using map plot lib our app has come to life it’s now time to add the saving functionality I want us to be able to save all of our table data as well as our chart let’s take a look at how we can achieve this does this look familiar well it should this is our method from our image app that we built in that image app we made a save method and the job of this method was when it was called it was going to save our newly edited photo within a new folder so remember we use the OS module to achieve this OS is our operating system we used our path to join or more specifically to link our directories together we’re going to use that now again we can also use the function make dur which allows us to make a new directory or specifically make make a new folder so start to think how could you create this how could you create a save method for this new app we’re making using the OS module let’s take a look at how we can do this here’s my code written now so in this method I want to be able to create a save folder and it’s going to save my Q tree view data as a CSV file okay then it’s going to take our chart and it’s going to save the chart as a PNG or as a picture so I need to do a few things here we need to get our existing directory remember we have used this before we use this and our image app our Q file dialogue and our get existing directory if we have our path then I want to make a new folder called saved in this folder this is where all of our charts and our CSV files will be saved within our app then what we could do is I can create a new file path and it just links just like the image app remember we created a new edited folder and we took this new folder and we linked it onto the end of our directory the same thing is happening here I create a new saved folder and I link that to the end of my directory now
that I have this new directory I’m taking this new directory and I am adding my CSV file that I’ve just created using my data to it now that we have that we can open this new file and I I want to write inside of this the name in my CSV file is going to be year and total it’s like two columns then for every Row in my tree view remember our treeview is called self. Model let me repeat that for every Row in my tree view I am going to get two things a year and a total and I’m taking this from the index the position of the First Column zero in my triw the second column is at position one that contains my total I can use the data method to do that once we have this new data for my row then I want to write in my CSV file I’m going to write two things with a comma in between they are going to be formatted to year year will be in the first one total will be in the second one that is what we see Happening Here pause the video read through break it down in our own words we’re going through every row into our Q Tree View and what we’re trying to do is we are going to get the data from the row and save that into our CSV file the code you see here this only applies to our CSV in order to save our chart it’s actually much easier thankfully matplot lib has a method for us called save fig this method works just like the save method we’ve used previously in our apps I can use Save fig and I’m going to give it the full folder name so previously the folder was saved here you could call it results and I’m giving the name to this picture as a friendly reminder at the end what you could do is you could include a q message box or a popup and just tell the user or give them some reassurance that hey yes your data has been saved you can use your Q message box with the information method and the warning method and we can link a few things and say hey congratulations your save was successful or no you actually didn’t select where you want to save to Let’s jump back into vs code and let’s begin to wrap things up the first thing we need to do to wrap up is to add our save functionality I’ll see you guys in our next lesson [Music] it’s time to add our saving functionality remember when we added the save method within our image editing app we needed something called Q file dialogue I’m going to import that right now we can next go down to the bottom of our class after our calc interest I’m going to go right here before reset I’m going to create a method called save data giving itself inside here I want to create a path or my directory path so let’s say directory path is equal to our qfile dialogue do get existing directory we’ve used this before you’ve seen it it’s going to allow us to choose that directory that we want inside here we want to give it self and I’m going to give it a caption so like select directory let’s make sure I spelled self correctly I’m then going to check if this is true so if I did indeed capture a directory we need to make sure that we selected something if we did I want to create a new folder so like a folder path now to do this remember I need OS we don’t have OS yet go up and let’s import OS right down here I’m just going to say import OS all right back down OS path I want to join together what do I want to join well I want to join the directory path that I’ve just made and then I want to join like a new folder so let’s call it like a saved right this is our saved folder it’s going to contain a CSV file as well as an image of our chart I’m then going to access my OS and let’s say OS make dur inside here we can say our folder path that’s the path to make we’re good we’re ready to go now that I have this new folder called save what I can try to do now is I want to save this CSV file and join that to my new path so let’s create a file path and say OS path I would like to join together what do I want to join together well I now have this new path called folder path and it’s going to add results which is going to be a CSV file we can now open this new file path I’ve just created which technically is a CV file we can give it the nickname file anytime that we use this word file now it’s like a nickname and it refers to this file this file is our working directory with our saved folder with our new CSV file so I want to open this CSV file giving it the nickname file inside the headers of this CSV file I’m going to write some stuff inside I’m going to write year and I’m going to write total before putting all the new information on a new line then for every Row in the range of my tree view so I want this Loop to repeat for however many items we have in our model which which is our treeview to do this I can just take our model and I’m going to say okay whatever that row count is of the model that’s how many times this Loop is going to repeat every time this Loop repeats I’m getting a year and I’m getting a total that I’m going to add into the CSV file my year how can I capture the year well let’s take our model let’s index let’s get the position I of the model the row is going to be whatever the current row we’re on that’s just the index of our for Loop what column is the year going to be in well the columns in year one which is at position zero next up let’s just get the data from that the total is going to be the same thing I can take my model I can index the current Row the column is one let’s get that data looks great inside our file I can take my file let’s write these new contents in our file so every row it’s capturing the year and the total and it’s going to write in the CSV line after line after line what do we want to write in every row well let’s just say I’m going to have data here it’s going to have a comma and then I’m going to have more data here I can then format that data how I want it to look and I want it to look like year and then total so let’s format it like that great we’ve saved the data from treeview as a CSV file what we can do now is I can take my map plot lib library and I’m going to say save fig I want to save my chart as a picture and I want to save it in my saved folder right finally at the end here let’s just give a nice little message to the user and say hey um either it’s saved or it didn’t save so just be like save results maybe that sounds nice what would you like to tell the user like uh results were saved to your folder then else I’m making this a part part of the initial condition so else I was not able to find a path to use then I’m going to give the user a warning and I need to alert them to this problem and say save results I can put no directory selected this looks great I’m actually done right here but there’s one thing we’re missing I have a save data method I should have a save button going up we don’t have a save button so I’m going to jump in here and I’m going to make one I’m going to call this save button let’s say save button is once again A Q push button going down let’s just add it right here in column one let’s say column one add widget let’s say save button okay then down with our events we can take our save button let’s give our have a final test all right let’s enter 12% let’s say 25,000 let’s say 20 years calculate let’s click save this is good it asks us where we want to save I’ll say open I’m given an error let’s take a look at how we saved this okay let’s do a few things here so I’m going to trash this the first thing I’m missing is I’m actually I need a command am I reading this file a pending or writing well I’m writing in this file the next thing let’s change this from makor let’s say makers instead make directories and if the directory already exists is that okay let’s just say yeah that’s that’s okay I can save multiple things to that file running my code again let’s say 12% 20,000 20 years calculate save where do we want to save it here is fine Open results we save to your folder okay I got that let me move my app or Shrink it let’s take a look now if you check your side folder you’re going to see results here’s my CSV okay and then you’re going to see the chart we saved as well it’s working our save functionality if I return to our app make it bigger we can press clear and we need to address our clear let’s just change clear to say draw because I want to draw a blank canvas and that’ll fix our issue okay this looks great guys I am so incredibly proud of how far you’ve come let’s jump in now we we going to add some final Advanced design cuz you’ve earned it I’ll see you guys in the next lesson where we’re going to talk about how we can add some styling to our application I’ll see you in the next [Music] video [Music] you can see that every app you’ve built you’ve added a little more styling every app we started with our warmup that random word app and The Styling you learned was the layout and the design you’ve gone to the calculator app we introduced Q font and how you can import a font to our app in the expense app we then introduced CSS and how you can use CSS and style your apps in pqt now for our final app let’s add in some more styling but this is going to be slightly more advanced now that we have a working app you can worry about that dark mode this is not something that you should worry about until you have a working product but it is a fun feature to add and it’s actually easier to implement than you may think in our interest rate calculator how can we add a dark mode Let’s jump in and find out how the last thing we want to wrap up with our app is we’re going to do a bonus dark mode we’re going to tweak any fonts we have add any colors and any styling when we first launch our app this is the template we see but then if we select our dark mode box it’s going to apply that filter to our app you also see that my chart has actually changed I’m going to show you how you can do that as well using map plot lib in order to get our dark mode implemented we will use our CSS styling do you remember how do we use CSS in pqt well you should remember our method set style sheet and we’re going to use that here as well I’m going to create a method and in this method I’m going to check if my checkbox is checked is checked is a method that checks the state of our Q combo box so it checks if you have clicked that now this doesn’t only work for Q combo box if you use a widget called Q radio button for radio buttons you can also use this method to check the state of that we have the method set stylesheet which is going to allow us for our stylesheet when our dark mode is checked I want my background to be a dark color of the whole app my Q labels q line edit Q push button they are going to take a lighter color then my Q Tree View is also going to be a lighter color text with a darker background let’s go back what does the app look like this is what it’s going to look like you can see that my font is now light my input boxes and my buttons Tree View is like this lightish dark gray the main app component is a very dark gray that’s what we’re actually applying here with our styling so remember in CSS we want to Target an element so for example H1 we want to affect anything with H1 and it’s going to take on the color of the text of white the font size the font family well it works the same in pi QT just remember that everything is a string I want to affect my entire app so finance app background color I only want to affect tree view all right so I Target Tree View here now that I created that dark mode I created that apply Styles method this method I am linking to an additional method specifically for toggling or turning on our dark mode we have our object that we made that’s a q checkbox now I want to use a new event this event is called State changed and this event triggers when we change the state of an object or to translate that and break it down this changes when we click a q combo box right I’m changing the state I’m clicking it I’m marking it that is what we want to connect to I want to connect to my toggle dark mode method in return I’m actually checking if my Q combo box is checked if it is it’s going to apply that style let’s wrap things up and let’s head back over into VSS code and wrap up our final application I’ll see you in that [Music] video we are now ready to implement some dark mode and add additional styling to make our app even more unique first thing I’m going to go up top and I want to import Q checkbox this is what we’re going to be using for our dark mode and then going down let’s just create one of an objects here let’s say let’s call this object dark mode and let’s say that is our Q checkbox this Q checkbox is going to say dark mode now that I have that we can add that into our layout so right here I’m going to say self. Row one let’s add in that new object we’ve made at the bottom of in it we have all of our events let’s take that dark mode and let’s say when the state is changed I want to connect to something now we need to make this something so I’m going to mark that right now after in it let’s create a bunch of space here I’m going to create a new method and I’m going to call this let’s call this apply Styles giving itself so first things first let’s set our style sheet remember this is how we do our styling in pqt so I’m going to create this property I’m calling this method set Style sheet and I’m going to give my app some qualities some background colors let me add those in so I’ve created the initial styles for my app when my app boots up it’s going to have these styles with it the initial Styles I can check if my dark mode so I can say if uh self. dark mode is checked we’re using this new method it’s going to check the state to see if it’s clicked so if it is I want to do something and I’m going to change these values so I can take this let’s put it inside and let me tweak these values so you can see now that when my dark mode is checked my background color is changing it was white now it’s this dark color my backgrounds for my other buttons my labels they’re changing as well as my tree view all of these are taking effect when my dark mode is checked great let’s apply these initial Styles remember when the app starts it’s going to have these Styles so I need to automatically apply these up inside in it let’s just go down here and in it and let’s say self. apply Styles and call that method great now carrying on we are going to create a final method and I’m going to call this toggle mode when this method is called the only thing that it’s doing is it’s going to apply Styles it’s going to call the method we made above here what happens is it’s going to hit this condition if it’s checked it’s going to change the styling up in our events right here I can now connect what do I want to connect to well I want to connect to this new method that I just made so let’s say self do toggle mode looking nice I think my app is ready for a quick run Let’s test it okay here’s our app you can see that the styling of everything looks a little different I’m going to click dark mode okay it is working this looks great I can turn that on turn that off turn that off okay let’s style a few more things I’m going to close the app I’m going to return to my Cal interest method right in here let’s go here I’m going to tweak a few things I’m going to say okay uh let’s make sure that every model is cleared before we calculate a new one and let’s take our model and let’s use this we have used this before we’ve said set horizontal header labels inside here here I want my chart to say year and I want my chart to say total okay then the last little tweak I’m going to do is I want my chart to actually have a style so I can take my map plot lib module and I’m going to say PLT cuz that’s referencing it I want to access style and I want to use now you can look up a few of the other styles they have cuz this has changed and it will continue to change but the style I’m I’m going to use and one of the more popular ones is called Seaborn so I’m going to add that in right there let’s run our app and do a final quick run through let’s say 8% interest with 50,000 for 15 years I’m going to click calculate it’s working I’m going to click clear okay we have everything working let’s say 8% let’s say 5,000 let’s say 15 years dark mode working calculate you can see my chart that was working the first time as well looks great I have my total label my year all right let’s click save where do we want to save it open we’re working this is incredible this is absolutely amazing we have shot for exactly what we want in our application you should feel so proud of yourself you have been introduced to so much in this course many new Advanced topics that don’t just include pqt I will see you guys in our next video congratulations and spend some time reviewing your code and seeing how everything came together there for us in the end I’ll see you in our next video [Music] congratulations you have just completed the building apps in Python with pqt course I am so proud of how far you’ve come throughout these last modules you have been introduced to a powerful framework that’s used to create apps in Python this framework is a bridge between C++ and Python and it’s a class-based framework which means you’ve used everything you’ve previously learned in the fundamentals of python and you’ve brought in that knowledge here to create class-based applications you now have four fledged Capstone projects you were introduced to pqt with our calculator app this taught you the layout and the design structure for building apps we let into our image editor app or photo QT here is where you learn that you can use multiple modules to create a single application you then were introduced to SQL in databases through our expense tracking app and for our final project we brought everything together with with our interest rate calculator and data visualization which is a powerful tool in Python I hope that you’ve had as much fun as I’ve had in this course and I look forward to seeing you in other courses that I may have in the zero to KN program congratulations and well done before jumping on to any other courses please spend the next week to hone in the skills you’ve learned and try creating your own project using everything that was taught in this course from data visualization to implementing CSS or adding a database into our applications I’ll see you guys around nicely done

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!

Leave a comment