PyQt4 Widgets

::-- zhuyj [2008-06-27 14:31:01]

1. PyQt4 Widgets

PyQt4组件

Widgets are basic building blocks of an application. The PyQt4 programming toolkit has a wide range of various widgets. Buttons, check boxes, sliders, list boxes etc. Everything a programmer needs for his job. In this section of the tutorial, we will describe several useful widgets.

1.1. QCheckBox

QCheckBox is a widget that has two states. On and Off. It is a box with a label. Whenever a checkbox is checked or cleared it emits the signal stateChanged().

   1 #!/usr/bin/python
   2 
   3 # checkbox.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class CheckBox(QtGui.QWidget):
  11     def __init__(self, parent=None):
  12         QtGui.QWidget.__init__(self, parent)
  13 
  14         self.setGeometry(300, 300, 250, 150)
  15         self.setWindowTitle('Checkbox')
  16 
  17         self.cb = QtGui.QCheckBox('Show title', self)
  18         self.cb.setFocusPolicy(QtCore.Qt.NoFocus)
  19         self.cb.move(10, 10)
  20         self.cb.toggle();
  21         self.connect(self.cb, QtCore.SIGNAL('stateChanged(int)'), self.changeTitle)
  22 
  23     def changeTitle(self, value):
  24         if self.cb.isChecked():
  25             self.setWindowTitle('Checkbox')
  26         else:
  27             self.setWindowTitle('')
  28 
  29 app = QtGui.QApplication(sys.argv)
  30 icon = CheckBox()
  31 icon.show()
  32 app.exec_()

In our example, we will create a checkbox that will toggle the window title.

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

This is the QCheckBox constructor.

 self.cb.setFocusPolicy(QtCore.Qt.NoFocus)

We connect the user defined changeTitle() method to the stateChanged() signal. The changeTitle() method will toggle the window title.

 self.connect(self.cb, QtCore.SIGNAL('stateChanged(int)'), self.changeTitle)

By default, the QCheckBox accepts focus. It is represented by a thin rectangle over the checkbox label. The rectangle looks awful, so I disable it by setting the widget focus policy to Qt.NoFocus.

 self.cb.toggle();

We set the window title, so we must also check the checkbox. By default, the window title is not set and the check box is unchecked.

QCheckBox

Figure: QCheckBox

1.2. ToggleButton

PyQt4 has no widget for a ToggleButton. To create a ToggleButton, we use a QPushButton in a special mode. ToggleButton is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.

   1 #!/usr/bin/python
   2 
   3 # togglebutton.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class ToggleButton(QtGui.QWidget):
  11     def __init__(self, parent=None):
  12         QtGui.QWidget.__init__(self, parent)
  13 
  14         self.color = QtGui.QColor(0, 0, 0) 
  15 
  16         self.setGeometry(300, 300, 280, 170)
  17         self.setWindowTitle('ToggleButton')
  18 
  19         self.red = QtGui.QPushButton('Red', self)
  20         self.red.setCheckable(True)
  21         self.red.move(10, 10)
  22 
  23         self.connect(self.red, QtCore.SIGNAL('clicked()'), self.setRed)
  24 
  25         self.green = QtGui.QPushButton('Green', self)
  26         self.green.setCheckable(True)
  27         self.green.move(10, 60)
  28 
  29         self.connect(self.green, QtCore.SIGNAL('clicked()'), self.setGreen)
  30 
  31         self.blue = QtGui.QPushButton('Blue', self)
  32         self.blue.setCheckable(True)
  33         self.blue.move(10, 110)
  34 
  35         self.connect(self.blue, QtCore.SIGNAL('clicked()'), self.setBlue)
  36 
  37         self.square = QtGui.QWidget(self)
  38         self.square.setGeometry(150, 20, 100, 100)
  39         self.square.setStyleSheet("QWidget { background-color: %s }" % self.color.name())
  40 
  41         QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('cleanlooks'))
  42 
  43     def setRed(self):
  44         if self.red.isChecked():
  45             self.color.setRed(255)
  46         else: self.color.setRed(0)
  47 
  48         self.square.setStyleSheet("QWidget { background-color: %s }" % self.color.name())
  49 
  50     def setGreen(self):
  51         if self.green.isChecked():
  52             self.color.setGreen(255)
  53         else: self.color.setGreen(0)
  54 
  55         self.square.setStyleSheet("QWidget { background-color: %s }" % self.color.name())
  56 
  57     def setBlue(self):
  58         if self.blue.isChecked():
  59             self.color.setBlue(255)
  60         else: self.color.setBlue(0)
  61 
  62         self.square.setStyleSheet("QWidget { background-color: %s }" % self.color.name())
  63 
  64 
  65 
  66 app = QtGui.QApplication(sys.argv)
  67 tb = ToggleButton()
  68 tb.show()
  69 app.exec_()

In our example, we create three ToggleButtons. We also create a QWidget. We set the background color of the QWidget to black. The togglebuttons will toggle the red, green and blue parts of the color value. The background color will depend on which togglebuttons we have pressed.

 self.color = QtGui.QColor(0, 0, 0)

This is the initial color value. No red, green and blue equals to black. Theoretically speaking, black is not a color after all.

 self.red = QtGui.QPushButton('Red', self)
 self.red.setCheckable(True)

To create a ToggleButton, we create a QPushButton and make it checkable by calling setCheckable() method.

 self.connect(self.red, QtCore.SIGNAL('clicked()'), self.setRed)

We connect a clicked() signal to our user defined method.

 QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('cleanlooks'))

I have set the style of the application to cleanlooks. I did it, because the default style for linux, plastique has a design bug. You cannot easily tell whether the ToggleButton is pressed or not. CleanLooks style is better.

 if self.red.isChecked():
     self.color.setRed(255)
 else: self.color.setRed(0)

We check, whether the button is pressed and change the color value accordingly.

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

To change the background color, we use stylesheets.

Figure: ToggleButton

1.3. QSlider, QLabel

QSlider is a widget that has a simple handle. This handle can be pulled back and forth. This way we are choosing a value for a specific task. Sometimes using a slider is more natural, than simply providing a number or using a spin box. QLabel displays text or image.

In our example we will show one slider and one label. This time, the label will display an image. The slider will control the label.

   1 #!/usr/bin/python
   2 
   3 # slider-label.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class SliderLabel(QtGui.QWidget):
  11     def __init__(self, parent=None):
  12         QtGui.QWidget.__init__(self, parent)
  13 
  14         self.setGeometry(300, 300, 250, 150)
  15         self.setWindowTitle('SliderLabel')
  16 
  17         self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
  18         self.slider.setFocusPolicy(QtCore.Qt.NoFocus)
  19         self.slider.setGeometry(30, 40, 100, 30)
  20         self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), self.changeValue)
  21 
  22 
  23         self.label = QtGui.QLabel(self)
  24         self.label.setPixmap(QtGui.QPixmap('mute.png'))
  25         self.label.setGeometry(160, 40, 80, 30)
  26 
  27 
  28     def changeValue(self, value):
  29         pos = self.slider.value()
  30 
  31         if pos == 0:
  32             self.label.setPixmap(QtGui.QPixmap('mute.png'))
  33         elif pos > 0 and pos <= 30:
  34             self.label.setPixmap(QtGui.QPixmap('min.png'))
  35         elif pos > 30 and pos < 80:
  36             self.label.setPixmap(QtGui.QPixmap('med.png'))
  37         else:
  38             self.label.setPixmap(QtGui.QPixmap('max.png'))
  39 
  40 app = QtGui.QApplication(sys.argv)
  41 icon = SliderLabel()
  42 icon.show()
  43 app.exec_()

In our example we simulate a volume control. By dragging the handle of a slider, we change a image on the label.

 self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)

Here we create a horizontal QSlider.

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

We create a Qlabel. And set an initial mute image to it.

 self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), self.changeValue)

We connect the valueChanged signal to the user defined changeValue() method.

{{{ pos = self.slider.value() }}} We get the position of the slider by calling the value() method. We change the image on the label accordingly.

Figure: Slider and Label

1.4. QProgressBar

A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that the user knows, that our task is progressing. The QProgressBar widget provides a horizontal or vertical progress bar in PyQt4 toolkit. The task is divided into steps. The programmer can set the minimum and maximum values for the progress bar. The default values are 0, 99.

   1 #!/usr/bin/python
   2 
   3 # progressbar.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class ProgressBar(QtGui.QWidget):
  11     def __init__(self, parent=None):
  12         QtGui.QWidget.__init__(self, parent)
  13 
  14         self.setGeometry(300, 300, 250, 150)
  15         self.setWindowTitle('ProgressBar')
  16 
  17         self.pbar = QtGui.QProgressBar(self)
  18         self.pbar.setGeometry(30, 40, 200, 25)
  19 
  20         self.button = QtGui.QPushButton('Start', self)
  21         self.button.setFocusPolicy(QtCore.Qt.NoFocus)
  22         self.button.move(40, 80)
  23 
  24         self.connect(self.button, QtCore.SIGNAL('clicked()'), self.onStart)
  25 
  26         self.timer = QtCore.QBasicTimer()
  27         self.step = 0;
  28 
  29 
  30     def timerEvent(self, event):
  31         if self.step >= 100:
  32             self.timer.stop()
  33             return
  34         self.step = self.step + 1
  35         self.pbar.setValue(self.step)
  36 
  37     def onStart(self):
  38         if self.timer.isActive():
  39             self.timer.stop()
  40             self.button.setText('Start')
  41         else:
  42             self.timer.start(100, self)
  43             self.button.setText('Stop')
  44 
  45 
  46 app = QtGui.QApplication(sys.argv)
  47 icon = ProgressBar()
  48 icon.show()
  49 app.exec_()

In our example we have a horizontal progress bar and a push button. The push button starts and stops the progress bar.

 self.pbar = QtGui.QProgressBar(self)

QProgressBar constructor.

 self.timer = QtCore.QBasicTimer()

To activate the progress bar, we use the timer object.

 self.timer.start(100, self)

To launch the timer events, we call the start() method. This method has two parameters. The timeout and the object, which will receive the events.

   1  def timerEvent(self, event):
   2      if self.step >= 100:
   3          self.timer.stop()
   4          return
   5      self.step = self.step + 1
   6      self.pbar.setValue(self.step)

Each QObject and its descendants has a QObject.timerEvent event handler. In order to react to timer events, we reimplement the event handler.

ProgressBar Figure: ProgressBar

1.5. QCalendarWidget

The QCalendarWidget provides a monthly based calendar widget. It allows a user to select a date in a simple and intuitive way.

   1 #!/usr/bin/python
   2 
   3 # calendar.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class Calendar(QtGui.QWidget):
  11     def __init__(self, parent=None):
  12         QtGui.QWidget.__init__(self, parent)
  13 
  14         self.setGeometry(300, 300, 350, 300)
  15         self.setWindowTitle('Calendar')
  16 
  17         self.cal = QtGui.QCalendarWidget(self)
  18         self.cal.setGridVisible(True)
  19         self.cal.move(20, 20)
  20         self.connect(self.cal, QtCore.SIGNAL('selectionChanged()'), self.showDate)
  21 
  22 
  23         self.label = QtGui.QLabel(self)
  24         date = self.cal.selectedDate()
  25         self.label.setText(str(date.toPyDate()))
  26         self.label.move(130, 260)
  27 
  28 
  29     def showDate(self):
  30         date = self.cal.selectedDate()
  31         self.label.setText(str(date.toPyDate()))
  32 
  33 
  34 app = QtGui.QApplication(sys.argv)
  35 icon = Calendar()
  36 icon.show()
  37 app.exec_()

The example has a calendar widget and a label widget. The currently selected date is displayed in the label widget.

 self.cal = QtGui.QCalendarWidget(self)

We construct a calendar widget.

 self.connect(self.cal, QtCore.SIGNAL('selectionChanged()'), self.showDate)

If we select a date from the widget, a selectionChanged() signal is emitted. We connect this method to the user defined showDate() method.

 def showDate(self):
     date = self.cal.selectedDate()
     self.label.setText(str(date.toPyDate()))

We retrieve the selected date calling the selectedDate() method. Then we transform the date object into string and set it to the label widget.

Calendar widget

Figure: Calendar widget

Widgets_插件 (last edited 2009-12-25 07:10:09 by localhost)