Book Image

Qt5 Python GUI Programming Cookbook

By : B. M. Harwani
Book Image

Qt5 Python GUI Programming Cookbook

By: B. M. Harwani

Overview of this book

PyQt is one of the best cross-platform interface toolkits currently available; it's stable, mature, and completely native. If you want control over all aspects of UI elements, PyQt is what you need. This book will guide you through every concept necessary to create fully functional GUI applications using PyQt, with only a few lines of code. As you expand your GUI using more widgets, you will cover networks, databases, and graphical libraries that greatly enhance its functionality. Next, the book guides you in using Qt Designer to design user interfaces and implementing and testing dialogs, events, the clipboard, and drag and drop functionality to customize your GUI. You will learn a variety of topics, such as look and feel customization, GUI animation, graphics rendering, implementing Google Maps, and more. Lastly, the book takes you through how Qt5 can help you to create cross-platform apps that are compatible with Android and iOS. You will be able to develop functional and appealing software using PyQt through interesting and fun recipes that will expand your knowledge of GUIs
Table of Contents (20 chapters)
Title Page
Dedication
Packt Upsell
Contributors
Preface
Index

Displaying options in the form of checkboxes


While creating applications, you may come across a situation where you need to provide several options for the user to select from. That is, you want the user to select one or more than one option from a set of options. In such situations, you need to make use of checkboxes. Let's find out more about checkboxes.

Getting ready

Whereas radio buttons allow only one option to be selected in a group, checkboxes allow you to select more than one option. That is, selecting a checkbox will not affect other checkboxes in the application. Checkboxes are displayed with a text label as an instance of the QCheckBox class. A checkbox can be in any of three states: selected (checked), unselected (unchecked), or tristate (unchanged). Tristate is a no change state; the user has neither checked nor unchecked the checkbox. 

Method application

The following are the methods provided by the QCheckBox class:

  • isChecked(): This method returns the Boolean value true if the checkbox is checked, and otherwise returns false.
  • setTristate(): If you don't want the user to change the state of the checkbox, you pass the Boolean value true to this method. The user will not be able to check or uncheck the checkbox.
  • setIcon(): This method is used to display an icon with the checkbox.
  • setText(): This method assigns text to the checkbox. To specify a shortcut key for the checkbox, precede the preferred character in the text with an ampersand. The shortcut character will appear as underlined.
  • setChecked(): In order to make a checkbox appear as checked by default, pass the Boolean value true to this method.

Signal description

The signals emitted by QCheckBox are as follows:

  • clicked(): This signal is emitted when a checkbox is activated (that is, pressed and released) or when its shortcut key is pressed
  • stateChanged(): This signal is emitted whenever a checkbox changes its state from checked to unchecked or vice versa

To understand the Check Box widget, let's assume that you run a restaurant where several food items, such as pizzas, are sold. The pizza is sold along with different toppings, such as extra cheese, extra olives, and so on, and the price of each topping is also mentioned with it. The user can select a regular pizza with one or more toppings. What you want is that when a topping is selected, the total price of the pizza, including the selected topping, is displayed.

How to do it...

The focus of this recipe is to understand how an action is initiated when the state of a checkbox changes from checked to unchecked or vice versa. Following is the step-by-step procedure to create such an application:

  1. Begin by creating a new application based on the Dialog without Buttons template.
  2. Drag and drop three Label widgets and three Check Box widgets onto the form.
  3. Set the text property of the first two Label widgets to Regular Pizza $10 and Select your extra toppings.
  4. In the Property Editor window, increase the font size of all three labels and checkboxes to increase their visibility in the application.
  5. Set the text property of the three checkboxes to Extra Cheese $1, Extra Olives $1, and Extra Sausages $2. The default object names of the three checkboxes are checkBox, checkBox_2, and checkBox_3.
  6. Change these to checkBoxCheese, checkBoxOlives, and checkBoxSausages, respectively.
  7. Set the objectName property of the Label widget to labelAmount.
  1. Save the application with the name demoCheckBox1.ui. Now, the form will appear as shown in the following screenshot:

The .ui (XML) file is then converted into Python code through the pyuic5 command utility. The Python code generated in thedemoCheckBox1.pyfile can be seen in the source code bundle of this book.

  1. Import the demoCheckBox1.py file, as a header file in our program to invoke the user interface design and to write code to calculate the total cost of regular pizza, along with the selected toppings, through a Label widget when the user selects or unselects any of the checkboxes.
  2. Let's name the program callCheckBox1.pyw; its code is shown here:
import sys
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from demoCheckBox1 import *
class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.checkBoxCheese.stateChanged.connect(self.
        dispAmount)
        self.ui.checkBoxOlives.stateChanged.connect(self.
        dispAmount)
        self.ui.checkBoxSausages.stateChanged.connect(self.
        dispAmount)
        self.show()
    def dispAmount(self):
        amount=10
        if self.ui.checkBoxCheese.isChecked()==True:
            amount=amount+1
        if self.ui.checkBoxOlives.isChecked()==True:
            amount=amount+1
        if self.ui.checkBoxSausages.isChecked()==True:
            amount=amount+2
        self.ui.labelAmount.setText("Total amount for pizza is 
        "+str(amount))
if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

How it works...

The stateChanged() event of checkboxes is connected to the dispAmount function, which will calculate the cost of the pizza along with the toppings selected. In the dispAmount function, you check the status of the checkboxes to find out whether they are checked or unchecked. The cost of the toppings whose checkboxes are checked is added and stored in the amount variable. Finally, the addition of the amount stored in the amount variable is displayed via labelAmount. On running the application, you get a dialog prompting you to select the toppings that you want to add to your regular pizza. On selecting any toppings, the amount of the regular pizza along with the selected toppings will be displayed on the screen, as shown in the following screenshot:

Note

The dispAmount function will be invoked every time the status of any checkbox changes. As a result, the total amount will be displayed via the Label widget, as soon as any checkbox is checked or unchecked.