In PyQt5 a toggle button is basically the push button in a special state. Push button is a button when we press it do some task and get back to the normal state it is similar to key board key when we press it, it do some thing and when we release it, it comes back to its original form. ToggleButton is a type of push button, but it has two states i.e on and off when we press it, it don’t comes back to the original state. Toggle button is similar to a electricity switch when we press it, it remains on and when we turn it off it remains in off position.
In order to create toggle button we have to do the following:
- Create a push button.
- Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box.
- Set calling method which get called when button is pressed.
- In calling method check if the button is checked or not.
- If button is checked change its color else set the default color to it.
Below is the implementation.
# importing the required libraries from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Window(QMainWindow):
def __init__( self ):
super ().__init__()
# set the title
self .setWindowTitle("Python")
# setting geometry
self .setGeometry( 100 , 100 , 600 , 400 )
# creating a push button
self .button = QPushButton("Toggle", self )
# setting geometry of button
self .button.setGeometry( 200 , 150 , 100 , 40 )
# setting checkable to true
self .button.setCheckable( True )
# setting calling method by button
self .button.clicked.connect( self .changeColor)
# setting default color of button to light-grey
self .button.setStyleSheet("background - color : lightgrey")
# show all the widgets
self .update()
self .show()
# method called by button
def changeColor( self ):
# if button is checked
if self .button.isChecked():
# setting background color to light-blue
self .button.setStyleSheet("background - color : lightblue")
# if it is unchecked
else :
# set background color back to light-grey
self .button.setStyleSheet("background - color : lightgrey")
# create pyqt5 app App = QApplication(sys.argv)
# create the instance of our Window window = Window()
# start the app sys.exit(App. exec ())
|
Output :