PYQT5 Tutorials-Components (7)

Source: Internet
Author: User

Components in the PYQT5 (widgets)

Component (widgets) is the base module for building an application. PYQT5 has a wide variety of components, including buttons, check buttons, slider bars, and list boxes. In this section of the tutorial, we will learn several useful components: a check button (Qcheckbox), a toggle button (ToggleButton), a slider bar (Qslider), a progress bar (ProgressBar), and a calendar component (Qcalendarwidget).

check box (Qcheckbox)

check box components have two states: checked and unchecked. It is made up of a selection box and a label. In an app, a check box is a typical component that is used to represent a valid or invalid state.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial In this example, a qcheckbox widgetis used to toggle th E title of a Window.author:Jan Bodnarwebsite:zetcode.com last Edited:january "" "Import Sysfrom pyqt5.qtwidgets Impo RT Qwidget, Qcheckbox, qapplicationfrom pyqt5.qtcore import qtclass Example (qwidget): def __init__ (self): su Per (). __init__ () Self.initui () def initui (self): cb = Qcheckbox (' Show title ' ', self) cb.move (cb.toggle) cb.stateChanged.connect (self.changetitle) self.se Tgeometry (() self.setwindowtitle (' Qcheckbox ') self.show () def changetitl E (Self, State): if state = = Qt.Checked:self.setWindowTitle (' Qcheckbox ') else:s     Elf.setwindowtitle (") if __name__ = = ' __main__ ': app = Qapplication (sys.argv) ex = Example () Sys.exit (App.exec_ ()) 

In our example, we created a check box to toggle the window caption.

CB = Qcheckbox (' Show title ', self)

This is the construction method of the Qcheckbox class.

Cb.toggle ()

We need to set the window caption, so we have to select the check box. If you do not select the check box, the check box is not selected by default so the window caption is not set.

Cb.stateChanged.connect (Self.changetitle)

Connect our custom Changetitle () Groove method to the statechanged signal. The Changetitle () method will be used to toggle the window caption.

def changetitle (self, State):        if state = = qt.checked:        self.setwindowtitle (' Qcheckbox ')    else:        Self.setwindowtitle (")

The status of the checkbox component is passed to the state parameter of the Changetitle () method. If the check box is selected, we set the window caption. Otherwise, we set the window caption to an empty string.

Figure:qcheckbox

Toggle button

The toggle button is a special mode for Qpushbutton. The toggle button has two states: pressed and not pressed. We can switch between the two states by clicking on it. The following sample shows the appropriate toggle button to appear.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial In this example, we create three toggle. They'll control the background colour of a qframe. Author:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, Qpushbu Tton, Qframe, qapplication) from Pyqt5.qtgui import Qcolorclass Example (qwidget): def __init__ (self): SUP               ER (). __init__ () Self.initui () def initui (self): Self.col = qcolor (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.move (10, Redb.clicked[bool].connect (self.setcolor) Blueb = Qpushbutton (' Blue ', self) blueb.setcheckable (Tr UE) Blueb.move (Blueb.clicked[bool].connect) (Self.setcolor) Self.square= Qframe (self) self.square.setGeometry ("Self.square.setStyleSheet", "Qwidget {Background-co Lor:%s} "% Self.col.name ()) Self.setgeometry ((), 280, Self.setwindowtitle (                ' Toggle button ') self.show () def setcolor (self, pressed): Source = Self.sender () If Pressed:val = 255 Else:val = 0 if source.text () = = "R Ed ": Self.col.setRed (val) elif source.text () = =" Green ": Self.col.setGreen (VA L) Else:self.col.setBlue (val) self.square.setStyleSheet ("Qframe {back Ground-color:%s} "% Self.col.name ()) If __name__ = = ' __main__ ': app = qapplication (sys. argv) ex = Example () sys.exit (App.exec_ ())

In our example, we created three toggle buttons and a qwidget component. We set the background color of the Qwidget component to black. The toggle button toggles the RGB values section in red, green, and blue. The background color of the Qwidget component will depend on which toggle button is pressed.

Self.col = Qcolor (0, 0, 0)    

Here is the initialization, so that the RGB value is black.

Redb = Qpushbutton (' Red ', self) redb.setcheckable (True) redb.move (10, 10)

To create a toggle button, create a Qpushbutton, and call the Setcheckable () method to make it available for selection.

Redb.clicked[bool].connect (Self.setcolor)

We connect the clicked signal to the method we define. We use the clicked signal to manipulate the Boolean value.

Source = Self.sender ()

We get a button that has a status switch.

If source.text () = = "Red":    self.col.setRed (val)   

In this case, if the switch is the red button, we update the color value of the red part of the RGB value.

Self.square.setStyleSheet ("Qwidget {background-color:%s}"%  self.col.name ())

We use style sheets to change the background color.

Figure:toggle button
slider Bar (qslider)

The slider bar (qslider) assembly has a simple adjustable handle. This handle can be dragged back and forth. We can use this method to select a specific value. Sometimes it's more natural to use a slider bar than to enter a number directly or use a numeric selection box, in our example below, we'll show a slider bar and a label. The label will display an image. The slider bar controls the label.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial This example shows a Qslider Widget.author:Jan bodnarw Ebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, Qslider, Qlabel, QAPPL        ication) from Pyqt5.qtcore import qtfrom Pyqt5.qtgui import Qpixmapclass Example (qwidget): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): SLD = Qslider (Qt.horiz Ontal, self) sld.setfocuspolicy (qt.nofocus) sld.setgeometry (max., +) sld.valuechanged[int].co Nnect (self.changevalue) Self.label = Qlabel (self) self.label.setPixmap (qpixmap (' Mute.png ')) s Elf.label.setGeometry (Self.setgeometry, Max, ()) Self.setwindowtitle (' QSl ', 280, Ider ') self.show () def changevalue (self, value): if value = = 0:self.label.set Pixmap (Qpixmap (' Mute.png') Elif value > 0 and Value <= 30:self.label.setpixmap (Qpixmap (' min.png ')) elif value ; and Value < 80:self.label.setpixmap (Qpixmap (' med.png ')) Else:self.label.setPixmap (QPi xMAP (' max.png ')) if __name__ = = ' __main__ ': app = Qapplication (sys.argv) ex = Example () sys.exit (APP.E         XEC_ ())

In our example, we simulated a volume controller. By dragging the handle of the slider bar, we can change the image of the label.

SLD = Qslider (Qt.horizontal, self)

Here we create a horizontal slider bar.

Self.label = Qlabel (self) self.label.setPixmap (qpixmap (' mute.png '))

We created a label component and set up an initial silent picture.

Sld.valuechanged[int].connect (Self.changevalue)

We valueChanged connect the signals to our customchangeValue()方法上。

if value = = 0:    self.label.setPixmap (Qpixmap (' mute.png ')) ...

This implements the values of the slider bar, and we set different label images. In the above code, if the value of the slider bar is equal to zero, we set the Mute.png picture for the label.

Figure:qslider Widget
Progress bar (Qprogressbar)

We need to use the progress bar component when we are dealing with long-consuming tasks. It's animated to let us know that the task is being processed. In PyQt5, the progress bar component provides a horizontal and vertical progress bar selection. Programmers can set the maximum and minimum values for the progress bar. The default value for the progress bar is 0~99.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial This example shows a Qprogressbar Widget.author:Jan Bo Dnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, Qprogressbar, QPU Shbutton, qapplication) from Pyqt5.qtcore import Qbasictimerclass Example (qwidget): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): Self.pbar = Qprogressbar (self        ) Self.pbar.setGeometry (40, 80) self.btn = Qpushbutton (' Start ', self) self.btn.move Self.btn.clicked.connect (self.doaction) Self.timer = Qbasictimer () self.step = 0 self. Setgeometry (280) self.setwindowtitle (' Qprogressbar ') self.show () def timer            Event (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.setText (' Start ') else:self.tim Er.start (self) self.btn.setText (' Stop ') if __name__ = = ' __main__ ': app = Qapplic ation (SYS.ARGV) ex = Example () sys.exit (App.exec_ ())

In our example there is a horizontal progress bar and a button. The button controls the start and stop of the slider bar.

Self.pbar = Qprogressbar (self)

This is how the slider bar class is constructed.

Self.timer = Qtcore.qbasictimer ()

We use the Timer object to activate the progress bar.

Self.timer.start (self)

To turn on the timer event, we call the start () method. This method has two parameters: timing time and the object receiving the timer event.

def timerevent (self, e):      if Self.step >=:            self.timer.stop ()        self.btn.setText (' finished ')        return            Self.step = self.step + 1    self.pbar.setValue (self.step)

Each Qobject class and its subclasses have a timerevent () event handler that is used to handle timed events. To give feedback on the timer event, we re-implemented the event handler function.

def doAction (self):      if Self.timer.isActive ():        self.timer.stop ()        self.btn.setText (' Start ')            else:        Self.timer.start (self)        self.btn.setText (' Stop ')

In the Doaction () method, we start and stop the timer.

Figure:qprogressbar
Calendar component (Qcalendarwidget)

The Qcalendarwidget class provides a month-based calendar component. It allows users to select dates in a simple and intuitive way.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial This example shows a qcalendarwidget Widget.author:Jan     Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import (Qwidget, Qcalendarwidget, Qlabel, qapplication) from Pyqt5.qtcore import Qdateclass Example (qwidget): def __init__ (self): Super (). __        Init__ () Self.initui () def initui (self): cal = Qcalendarwidget (self)  Cal.setgridvisible (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 (130, 260)                    Self.setgeometry (Self.setwindowtitle) (' Calendar ') self.show () def showdate (self, date): Self.lbl.setText (date.tostring ()) If __name__ = = ' __mai N__ ': app = QapplIcation (SYS.ARGV) ex = Example () sys.exit (App.exec_ ()) 

The example above shows a calendar component and a label component. The feature is that the date selected in the calendar is displayed in the label component.

Cal = Qcalendarwidget (self)

Create the Qcalendarwidget class.

Cal.clicked[qdate].connect (Self.showdate)

If we select a date on the component, the clicked[QDate] signal will be emitted. We connect this signal to the custom Showdate () method.

def showdate (self, date):             Self.lbl.setText (date.tostring ())

We retrieve the selected date through the SelectedDate () method. We then turn the selected date object into a string to display on the label component.

PYQT5 Tutorials-Components (7)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.