Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Qt5 Python GUI Programming Cookbook

You're reading from   Qt5 Python GUI Programming Cookbook Building responsive and powerful cross-platform applications with PyQt

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher Packt
ISBN-13 9781788831000
Length 462 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
B. M. Harwani B. M. Harwani
Author Profile Icon B. M. Harwani
B. M. Harwani
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Creating a User Interface with Qt Components FREE CHAPTER 2. Event Handling - Signals and Slots 3. Working with Date and Time 4. Understanding OOP Concepts 5. Understanding Dialogs 6. Understanding Layouts 7. Networking and Managing Large Documents 8. Doing Asynchronous Programming in Python 9. Database Handling 10. Using Graphics 11. Implementing Animation 12. Using Google Maps 13. Running Python Scripts on Android and iOS 14. Other Books You May Enjoy

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 the demoCheckBox1.py file 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:

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.
You have been reading a chapter from
Qt5 Python GUI Programming Cookbook
Published in: Jul 2018
Publisher: Packt
ISBN-13: 9781788831000
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image