PyQt5系列教程(七)控件

/

软硬件环境

  • Windows 10
  • Python 3.4.2
  • PyQt 5.5.1
  • PyCharm 5.0.4

前言

控件是PyQt应用程序的基石。PyQt5自带很多不同的控件,包括像button、check box、slider等等。在本节中我们将学习几个非常有用的控件:QCheckBox、ToggleButton、QSlider、QProgressBar和QCalendarWidget。

QCheckBox

一个QCheckBox会有2种状态:选中和为选中。它有一个选择框和一个label组成,它常常被用来表示应用的某些特性是可启用或不启用的。

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'djstava@gmail.com'
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, a QCheckBox widget
  6. is used to toggle the title of a window.
  7. author: Jan Bodnar
  8. website: zetcode.com
  9. last edited: January 2015
  10. """
  11. import sys
  12. from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication
  13. from PyQt5.QtCore import Qt
  1. class Example(QWidget):
  1. def __init__(self):
  2. super().__init__()
  3. self.initUI()
  1. def initUI(self):
  1. cb = QCheckBox('Show title', self)
  2. cb.move(20, 20)
  3. cb.toggle()
  4. cb.stateChanged.connect(self.changeTitle)
  5. self.setGeometry(300, 300, 250, 150)
  6. self.setWindowTitle('QCheckBox')
  7. self.show()
  1. def changeTitle(self, state):
  1. if state == Qt.Checked:
  2. self.setWindowTitle('QCheckBox')
  3. else:
  4. self.setWindowTitle('')
  1. if __name__ == '__main__':
  1. app = QApplication(sys.argv)
  2. ex = Example()
  3. sys.exit(app.exec_())

程序执行效果如下

qcheckbox_01

在这个例子中,我们创建了一个选择框,它状态的变化会引起窗口标题的变化。

  1. cb = QCheckBox('Show title', self)

这条语句是QCheckBox的构造函数,它的label是”Show title”。

  1. cb.toggle()

设置默认是选中状态

  1. cb.stateChanged.connect(self.changeTitle)

将自定义的槽函数changeTitle和信号stateChanged绑定起来,槽函数changeTitle会改变窗口的标题

  1. def changeTitle(self, state):
  1. if state == Qt.Checked:
  2. self.setWindowTitle('QCheckBox')
  3. else:
  4. self.setWindowTitle('')

选中状态下,窗口标题设置为”QCheckBox”,否则设置为空

Toggle button

Toggle button是一种特殊的QPushButton(按钮),它也有2种状态,按下和未按下,我们通过点击它来区分2种不同的状态。实际很多情况下都会用到它。

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'djstava@gmail.com'
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we create three toggle buttons.
  6. They will control the background colour of a
  7. QFrame.
  8. author: Jan Bodnar
  9. website: zetcode.com
  10. last edited: January 2015
  11. """
  12. import sys
  13. from PyQt5.QtWidgets import (QWidget, QPushButton,
  14. QFrame, QApplication)
  15. from PyQt5.QtGui import QColor
  1. class Example(QWidget):
  1. def __init__(self):
  2. super().__init__()
  3. self.initUI()
  1. def initUI(self):
  1. self.col = QColor(0, 0, 0)
  1. redb = QPushButton('Red', self)
  2. redb.setCheckable(True)
  3. redb.move(10, 10)
  4. redb.clicked[bool].connect(self.setColor)
  5. redb = QPushButton('Green', self)
  6. redb.setCheckable(True)
  7. redb.move(10, 60)
  8. redb.clicked[bool].connect(self.setColor)
  9. blueb = QPushButton('Blue', self)
  10. blueb.setCheckable(True)
  11. blueb.move(10, 110)
  12. blueb.clicked[bool].connect(self.setColor)
  13. self.square = QFrame(self)
  14. self.square.setGeometry(150, 20, 100, 100)
  15. self.square.setStyleSheet("QWidget { background-color: %s }" %
  16. self.col.name())
  17. self.setGeometry(300, 300, 280, 170)
  18. self.setWindowTitle('Toggle button')
  19. self.show()
  1. def setColor(self, pressed):
  1. source = self.sender()
  1. if pressed:
  2. val = 255
  3. else: val = 0
  4. if source.text() == "Red":
  5. self.col.setRed(val)
  6. elif source.text() == "Green":
  7. self.col.setGreen(val)
  8. else:
  9. self.col.setBlue(val)
  10. self.square.setStyleSheet("QFrame { background-color: %s }" %
  11. self.col.name())
  1. if __name__ == '__main__':
  1. app = QApplication(sys.argv)
  2. ex = Example()
  3. sys.exit(app.exec_())

代码执行效果如下所示

toggleButton_01

本例中我们创建了3个toggle button和一个QWidget,将QWidget的背景色设置成了黑色,左边的3个toggle button会改变右边QWidget的颜色。

  1. redb = QPushButton('Red', self)
  2. redb.setCheckable(True)

为了创建toggle button,我们首先创建一个QPushButton,然后调用方法setCheckable()。后面的信号和槽的绑定,相信大家都很熟悉了,这里就不说了。

QSlider

QSlider是一个滑动条,允许你在某一范围内拖动。有时候这种方式比输入数字或者使用spin box更加自然。

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'djstava@gmail.com'
  3. """
  4. ZetCode PyQt5 tutorial
  5. This example shows a QSlider widget.
  6. author: Jan Bodnar
  7. website: zetcode.com
  8. last edited: January 2015
  9. """
  10. import sys
  11. from PyQt5.QtWidgets import (QWidget, QSlider,
  12. QLabel, QApplication)
  13. from PyQt5.QtCore import Qt
  14. from PyQt5.QtGui import QPixmap
  1. class Example(QWidget):
  1. def __init__(self):
  2. super().__init__()
  3. self.initUI()
  1. def initUI(self):
  1. sld = QSlider(Qt.Horizontal, self)
  2. sld.setFocusPolicy(Qt.NoFocus)
  3. sld.setGeometry(30, 40, 100, 30)
  4. sld.valueChanged[int].connect(self.changeValue)
  5. self.label = QLabel(self)
  6. self.label.setPixmap(QPixmap('mute.png'))
  7. self.label.setGeometry(160, 40, 80, 30)
  8. self.setGeometry(300, 300, 280, 170)
  9. self.setWindowTitle('QSlider')
  10. self.show()
  1. def changeValue(self, value):
  1. if value == 0:
  2. self.label.setPixmap(QPixmap('mute.png'))
  3. elif value > 0 and value <= 30:
  4. self.label.setPixmap(QPixmap('min.png'))
  5. elif value > 30 and value < 80:
  6. self.label.setPixmap(QPixmap('med.png'))
  7. else:
  8. self.label.setPixmap(QPixmap('max.png'))
  1. if __name__ == '__main__':
  1. app = QApplication(sys.argv)
  2. ex = Example()
  3. sys.exit(app.exec_())

代码运行效果如下所示,我这没有加入图片,所以看不到右侧图片的变化。我这里只解释下QSlider的使用,信号和曹函数跟之前都是一样的。

qslider_01

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

QSlider构造函数中传入Qt.Horizontal,创建的是一个横向的slider

QProgressBar

ProgressBar一般用来表示任务的进度,也有横向和众向之分。你可以设置进度条的最小值和最大值,默认是0和99。

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'djstava@gmail.com'
  3. """
  4. ZetCode PyQt5 tutorial
  5. This example shows a QProgressBar widget.
  6. author: Jan Bodnar
  7. website: zetcode.com
  8. last edited: January 2015
  9. """
  10. import sys
  11. from PyQt5.QtWidgets import (QWidget, QProgressBar,
  12. QPushButton, QApplication)
  13. from PyQt5.QtCore import QBasicTimer
  1. class Example(QWidget):
  1. def __init__(self):
  2. super().__init__()
  3. self.initUI()
  1. def initUI(self):
  1. self.pbar = QProgressBar(self)
  2. self.pbar.setGeometry(30, 40, 200, 25)
  3. self.btn = QPushButton('Start', self)
  4. self.btn.move(40, 80)
  5. self.btn.clicked.connect(self.doAction)
  6. self.timer = QBasicTimer()
  7. self.step = 0
  8. self.setGeometry(300, 300, 280, 170)
  9. self.setWindowTitle('QProgressBar')
  10. self.show()
  1. def timerEvent(self, e):
  1. if self.step >= 100:
  2. self.timer.stop()
  3. self.btn.setText('Finished')
  4. return
  5. self.step = self.step + 1
  6. self.pbar.setValue(self.step)
  1. def doAction(self):
  1. if self.timer.isActive():
  2. self.timer.stop()
  3. self.btn.setText('Start')
  4. else:
  5. self.timer.start(100, self)
  6. self.btn.setText('Stop')
  1. if __name__ == '__main__':
  1. app = QApplication(sys.argv)
  2. ex = Example()
  3. sys.exit(app.exec_())

代码运行效果如下所示

qprogressbar_01

这里使用一个计时器来启动进度条

  1. self.timer = QtCore.QBasicTimer()
  1. def timerEvent(self, e):
  1. if self.step >= 100:
  1. self.timer.stop()
  2. self.btn.setText('Finished')
  3. return
  4. self.step = self.step + 1
  5. self.pbar.setValue(self.step)

每个QObject及其子类都有个timerEvent()事件处理器,需要我们重新实现,它的第一个参数是超时时间

QCalendarWidget

QCalendarWidget是一个以月份为基础的日历控件,用来供用户选择日期

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'djstava@gmail.com'
  3. """
  4. ZetCode PyQt5 tutorial
  5. This example shows a QCalendarWidget widget.
  6. author: Jan Bodnar
  7. website: zetcode.com
  8. last edited: January 2015
  9. """
  10. import sys
  11. from PyQt5.QtWidgets import (QWidget, QCalendarWidget,
  12. QLabel, QApplication)
  13. from PyQt5.QtCore import QDate
  1. class Example(QWidget):
  1. def __init__(self):
  2. super().__init__()
  3. self.initUI()
  1. def initUI(self):
  1. cal = QCalendarWidget(self)
  2. cal.setGridVisible(True)
  3. cal.move(20, 20)
  4. cal.clicked[QDate].connect(self.showDate)
  5. self.lbl = QLabel(self)
  6. date = cal.selectedDate()
  7. self.lbl.setText(date.toString())
  8. self.lbl.move(130, 260)
  9. self.setGeometry(300, 300, 350, 300)
  10. self.setWindowTitle('Calendar')
  11. self.show()
  1. def showDate(self, date):
  1. self.lbl.setText(date.toString())
  1. if __name__ == '__main__':
  1. app = QApplication(sys.argv)
  2. ex = Example()
  3. sys.exit(app.exec_())

代码运行效果如下所示

qcalendarwidget_01

参考文献

http://zetcode.com/gui/pyqt5/widgets/

转载请注明作者和出处,并添加本页链接。
原文链接: blog.xugaoxiang.com/31

给我留言