Hardware and Software Environment
- Windows 10
- Python 3.4.2
- PyQt 5.5.1
- Pycharm 5.0.4
Objective
Controls are the cornerstone of PYQT applications. PyQt5 comes with many different controls, including buttons, check boxes, sliders, and so on. In this section we will learn a few very useful controls: Qcheckbox, ToggleButton, Qslider, Qprogressbar, and Qcalendarwidget.
Qcheckbox
A qcheckbox will have 2 statuses: checked and selected. It has a selection box and a label, which is often used to indicate that certain features of the app are either enabled or not enabled.
# -*- coding: utf-8 -*-__author__ = ‘[email protected]‘"""ZetCode PyQt5 tutorial In this example, a QCheckBox widgetis used to toggle the title of a window.author: Jan Bodnarwebsite: zetcode.com last edited: January 2015"""import sysfrom PyQt5.QtWidgets import QWidget, QCheckBox, QApplicationfrom PyQt5.QtCore import Qtclass Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): cb = QCheckBox(‘Show title‘, self) cb.move(20, 20) cb.toggle() cb.stateChanged.connect(self.changeTitle) self.setGeometry(300, 300, 250, 150) self.setWindowTitle(‘QCheckBox‘) self.show() def changeTitle(self, state): if state == Qt.Checked: self.setWindowTitle(‘QCheckBox‘) else: self.setWindowTitle(‘‘)if __name__ == ‘__main__‘: app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
Program execution effect is as follows
In this example, we create a selection box that changes the status of the window to change the caption.
cb = QCheckBox(‘Show title‘, self)
This statement is the constructor of Qcheckbox, and its label is "Show title".
cb.toggle()
Set default is checked state
cb.stateChanged.connect(self.changeTitle)
Bind the custom slot function changetitle to the signal statechanged, and the slot function Changetitle Change the caption of the window
def changeTitle(self, state):if state == Qt.Checked: self.setWindowTitle(‘QCheckBox‘)else: self.setWindowTitle(‘‘)
When selected, the window caption is set to "Qcheckbox", otherwise it is set to empty
Toggle button
Toggle button is a special Qpushbutton (button), it also has 2 states, pressed and not pressed, we can distinguish 2 different states by clicking on it. It can be used in many cases.
#-*-Coding:utf-8-*-__author__ = ' [email protected] ' "" "Zetcode PyQt5 Tutorialin This example, we create three Togg Le buttons. They would control the background colour of AQFrame.author:Jan Bodnarwebsite:zetcode.comlast edited:january "" "Impor T sysfrom pyqt5.qtwidgets Import (Qwidget, Qpushbutton, Qframe, qapplication) from Pyqt5.qtgui import Qcolorclass Exampl E (qwidget): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): Self.col = Q Color (0, 0, 0) redb = Qpushbutton (' Red ', self) redb.setcheckable (True) Redb.move (Ten) Redb. Clicked[bool].connect (self.setcolor) redb = Qpushbutton (' Green ', self) redb.setcheckable (True) redb.m Ove (Ten) Redb.clicked[bool].connect (self.setcolor) Blueb = Qpushbutton (' Blue ', self) blueb.setchec Kable (True) blueb.move (+) Blueb.clicked[bool].connect (self.setcolor) Self.square = Qframe (self) Self.Square.setgeometry (Self.square.setStyleSheet) ("Qwidget {background-color:%s}"% sel F.col.name ()) Self.setgeometry (() self.setwindowtitle (' Toggle button ') self.show () (280) def setcolor (self, pressed): Source = Self.sender () If pressed:val = 255 Else:val = 0 If source.text () = = "Red": Self.col.setRed (val) elif source.text () = = "Green": self.co L.setgreen (Val) else:self.col.setBlue (val) self.square.setStyleSheet ("Qframe {background-color: %s} "% Self.col.name ()) If __name__ = = ' __main__ ': app = Qapplication (sys.argv) ex = Example () sys.ex It (APP.EXEC_ ())
The code execution effect is as follows
In this example we created 3 toggle buttons and a qwidget, set the qwidget background color to black, and the 3 toggle button on the left to change the color of the qwidget on the right.
redb = QPushButton(‘Red‘, self)redb.setCheckable(True)
In order to create the toggle button, we first create a Qpushbutton and then call the method Setcheckable (). After the signal and slot binding, I believe everyone is very familiar with, here will not say.
Qslider
Qslider is a slider bar that allows you to drag within a range. Sometimes this is more natural than entering numbers or using spin box.
#-*-Coding:utf-8-*-__author__ = ' [email protected] ' "" "Zetcode PyQt5 Tutorial This example shows a Qslider widget. Author:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, Qslider , Qlabel, qapplication) from Pyqt5.qtcore import qtfrom Pyqt5.qtgui import Qpixmapclass Example (qwidget): Def __init __ (self): Super (). __init__ () Self.initui () def initui (self): SLD = Qslider (qt.horizontal, SE LF) Sld.setfocuspolicy (qt.nofocus) sld.setgeometry (+, +, +) Sld.valuechanged[int].connect (sel F.changevalue) Self.label = Qlabel (self) self.label.setPixmap (qpixmap (' mute.png ')) Self.label.setGeom Etry (Self.setgeometry, Max, ()) Self.setwindowtitle (' Qslider ') self.show () (280) def changevalue (self, value): if value = = 0:self.label.setpixmap (Qpixmap (' mute.png ')) Elif V Alue > 0 and Value ≪= 30:self.label.setpixmap (Qpixmap (' min.png ')) elif value > value < 80:SELF.L Abel.setpixmap (Qpixmap (' med.png ')) Else:self.label.setPixmap (Qpixmap (' max.png ')) if __name__ = = ' __main_ _ ': App = Qapplication (sys.argv) ex = Example () sys.exit (App.exec_ ())
The code runs as shown below, and I'm not adding a picture, so I can't see the change in the picture on the right. Here I only explain the use of qslider, the signal and CAO functions are the same as before.
sld = QSlider(Qt.Horizontal, self)sld.setFocusPolicy(Qt.NoFocus)sld.setGeometry(30, 40, 100, 30)sld.valueChanged[int].connect(self.changeValue)
The Qslider constructor passes in the qt.horizontal, creating a horizontal slider
Qprogressbar
ProgressBar is generally used to indicate the progress of a task, as well as horizontal and public. You can set the minimum and maximum values for the progress bar, which defaults to 0 and 99.
#-*-Coding:utf-8-*-__author__ = ' [email protected] ' "" "Zetcode PyQt5 tutorialthis example shows a Qprogressbar wid Get.author:Jan Bodnarwebsite:zetcode.comlast edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, QPr Ogressbar, Qpushbutton, qapplication) from Pyqt5.qtcore import Qbasictimerclass Example (qwidget): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): Self.pbar = Qprogressbar (self) SELF.PBA R.setgeometry (max., +) self.btn = Qpushbutton (' Start ', self) self.btn.move (+) self.btn.c Licked.connect (self.doaction) Self.timer = Qbasictimer () self.step = 0 self.setgeometry (300, 300, 280 , Self.setwindowtitle (' Qprogressbar ') self.show () def timerevent (self, E): if Self.step >= 100:self.timer.stop () Self.btn.setText (' finished ') return self.step = Self.step + 1 Self.pbar.setVAlue (Self.step) def doAction (self): if Self.timer.isActive (): Self.timer.stop () self.btn.s Ettext (' Start ') Else:self.timer.start (+, self) self.btn.setText (' Stop ') if __name__ = = ' __m Ain__ ': app = Qapplication (sys.argv) ex = Example () sys.exit (App.exec_ ())
The code works as shown below
Here a timer is used to start the progress bar
self.timer = QtCore.QBasicTimer()def timerEvent(self, e):if self.step >= 100: self.timer.stop() self.btn.setText(‘Finished‘) returnself.step = self.step + 1self.pbar.setValue(self.step)
Each qobject and its subclasses have a timerevent () event handler that needs to be re-implemented, and its first parameter is the time-out
Qcalendarwidget
Qcalendarwidget is a month-based calendar control that is used by the user to select a date
#-*-Coding:utf-8-*-__author__ = ' [email protected] ' "" "Zetcode PyQt5 tutorialthis example shows a qcalendarw Idget widget.author:Jan Bodnarwebsite:zetcode.comlast edited:january "" "Import sysfrom pyqt5.qtwidgets import (qwi Dget, Qcalendarwidget, Qlabel, qapplication) from Pyqt5.qtcore import Qdateclass Example (qwidget): def __init__ (self) : Super (). __init__ () Self.initui () def initui (self): cal = Qcalendarwidget (self) Cal.setgri Dvisible (True) Cal.move (a) cal.clicked[qdate].connect (self.showdate) Self.lbl = Qlabel (self) Date = Cal.selecteddate () self.lbl.setText (date.tostring ()) Self.lbl.move (260) Self.setgeome Try (self.setwindowtitle) (' Calendar ') self.show () def showdate (self, date): Self . Lbl.settext (Date.tostring ()) If __name__ = = ' __main__ ': app = Qapplication (sys.argv) ex = Example () sys.exit (app. Exec_ ())
The code works as shown below
Reference documents
http://zetcode.com/gui/pyqt5/widgets/
PYQT5 Series Tutorials (vii) controls