Common controls for PyQT learning

Controls are like the bricks of the application house. PyQt5 has many controls, such as buttons, radio boxes, sliders, check boxes and so on. In this chapter, we will introduce some useful controls: QCheckBox, ToggleButton, QSlider, QProgressBarand QCalendarWidget.

QCheckBox

QCheckBoxA component has two states: on and off. Usually used with tags, used in the scene of activating and deactivating some options.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, a QCheckBox widget
is used to toggle the title of a window.

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication
from PyQt5.QtCore import Qt
import sys

class 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_())

In this example, there is a radio button that toggles the window title.

cb = QCheckBox('Show title', self)

This is QCheckBoxthe constructor.

cb.toggle()

To set the window title, we check the state of the radio button. By default, the window has no title and the radio box is unchecked.

cb.stateChanged.connect(self.changeTitle)

Associate changeTitle()methods with stateChangedsignals. In this way, changeTitle()the window title can be switched.

def changeTitle(self, state):

    if state == Qt.Checked:
        self.setWindowTitle('QCheckBox')
    else:
        self.setWindowTitle('')

The state of the control is changeTitle()controlled by the method. If the space is selected, we add a title to the window, and if it is not selected, we clear the title.

Program display:

switch button

A toggle button is QPushButtona special mode of that. It has only two states: pressed and not pressed. We switch between the two states when clicking, and this function is used in many scenarios.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we create three toggle buttons.
They will control the background color of a 
QFrame. 

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

from PyQt5.QtWidgets import (QWidget, QPushButton, 
    QFrame, QApplication)
from PyQt5.QtGui import QColor
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        self.col = QColor(0, 0, 0)       

        redb = QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 10)

        redb.clicked[bool].connect(self.setColor)

        greenb = QPushButton('Green', self)
        greenb.setCheckable(True)
        greenb.move(10, 60)

        greenb.clicked[bool].connect(self.setColor)

        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 110)

        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s }" %  
            self.col.name())

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Toggle button')
        self.show()


    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.col.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.exit(app.exec_())

We create a toggle button and a QWidget, and QWidgetset the background to black. Click the different switching buttons, the background color will switch between red, green, and blue (and you can see the effect of color synthesis, not just color coverage).

self.col = QColor(0, 0, 0)

Set the color to black.

redb = QPushButton('Red', self)
redb.setCheckable(True)
redb.move(10, 10)

Create one QPushButton, and then call its setCheckable()method to program the button as a toggle button.

redb.clicked[bool].connect(self.setColor)

Associate the click signal with the function we defined, here is to convert the click event into a Boolean value.

source = self.sender()

Get the button that was clicked.

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

If the button labeled "red" is clicked, change the color to the preset corresponding color.

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

Use a style sheet (that is, SS of CSS) to change the background color

Program display:

slider

QSliderIt is a component with a small slider, which can be dragged and slid back and forth. This is often used to modify some values ​​with a range, which is much more convenient than a text box or a text box (spin box) that can be increased or decreased by clicking.

This example is shown with a slider and a label. The label is an image, and the slider controls (the value of) the label.

Prepare four icons representing mute, low volume, medium volume, and high volume, and the file names are mute.png, min.png, med.png, and max.png.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This example shows a QSlider widget.

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

from PyQt5.QtWidgets import (QWidget, QSlider, 
    QLabel, QApplication)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(30, 40, 100, 30)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('mute.png'))
        self.label.setGeometry(160, 40, 80, 30)

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QSlider')
        self.show()


    def changeValue(self, value):

        if value == 0:
            self.label.setPixmap(QPixmap('mute.png'))
        elif value > 0 and value <= 30:
            self.label.setPixmap(QPixmap('min.png'))
        elif value > 30 and value < 80:
            self.label.setPixmap(QPixmap('med.png'))
        else:
            self.label.setPixmap(QPixmap('max.png'))


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Here is the simulated fader. Drag the slider to change the image of the label position.

sld = QSlider(Qt.Horizontal, self)

Create a level QSlider.

self.label = QLabel(self)
self.label.setPixmap(QPixmap('mute.png'))

Create a QLabelcomponent and set a mute icon to it.

sld.valueChanged[int].connect(self.changeValue)

Associate valueChangedsignals with changeValue()methods.

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

Replace the picture of the label position according to the size of the volume value. This code is: If the volume is 0, replace the picture with mute.png.

Program display:

progress bar

The progress bar is used to show the progress of the task (I don't want to say that). Its scrolling keeps the user informed of the progress of the task. QProgressBarThe component provides two kinds of progress bars, horizontal and vertical. The progress bar can set the maximum and minimum values, and the default is 0~99.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This example shows a QProgressBar widget.

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

from PyQt5.QtWidgets import (QWidget, QProgressBar, 
    QPushButton, QApplication)
from PyQt5.QtCore import QBasicTimer
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)

        self.btn = QPushButton('Start', self)
        self.btn.move(40, 80)
        self.btn.clicked.connect(self.doAction)

        self.timer = QBasicTimer()
        self.step = 0

        self.setGeometry(300, 300, 280, 170)
        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.setText('Start')
        else:
            self.timer.start(100, self)
            self.btn.setText('Stop')


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

We create a horizontal progress bar and a button that starts and stops the progress bar.

self.pbar = QProgressBar(self)

Create a new QProgressBarconstructor.

self.timer = QtCore.QBasicTimer()

Control the progress bar with time.

self.timer.start(100, self)

Call start()method to load a time event. This method has two parameters: expiration time and event receiver.

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)

Each QObjectobject and the object it inherits from has an timerEvent()event handler. In order to trigger the event, we override this method.

def doAction(self):

    if self.timer.isActive():
        self.timer.stop()
        self.btn.setText('Start')

    else:
        self.timer.start(100, self)
        self.btn.setText('Stop')

The methods inside doAction()are used to control start and stop.

Program display:

calendar

QCalendarWidgetProvides a month-based calendar plugin that is easy and intuitive.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This example shows a QCalendarWidget widget.

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

from PyQt5.QtWidgets import (QWidget, QCalendarWidget, 
    QLabel, QApplication, QVBoxLayout)
from PyQt5.QtCore import QDate
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        vbox = QVBoxLayout(self)

        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(self.showDate)

        vbox.addWidget(cal)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())

        vbox.addWidget(self.lbl)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 350, 300)
        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_())

This example consists of a date component and a label component, and the label displays the selected date.

cal = QCalendarWidget(self)

Create one QCalendarWidget.

cal.clicked[QDate].connect(self.showDate)

When a date is selected, QDatethe click signal is triggered, and this signal showDate()is associated with our own defined method.

def showDate(self, date):     

    self.lbl.setText(date.toString())

Use selectedDate()the method to get the selected date, then convert the date object into a string and display it in the label.

Program display:

おすすめ

転載: blog.csdn.net/zy_dreamer/article/details/132700461