First programs in PyQt4 toolkit

::-- zhuyj [2008-06-06 01:37:11]

1. First programs in PyQt4 toolkit 初次使用PyQt4工具包编程

In this sections we will learn some basic functionality. The explanation will be slow, as if we would talk to a child. The first steps of a child are awkward, so are the very first attempts of a newbie programmer. Remember, there are no stupid people. There are only lazy people and people, that are not persistent enough.

1.1. Simple example 简单的例子

简单的例子

The code example is very simplistic. It only shows a small window. Yet we can do a lot with this window. We can resize it. Maximize it. Minimize it. This requires a lot of coding. Someone already coded this functionality. Because it repeats in most applications, there is no need to code it over again So it has been hidden from a programmer. PyQt is a high level toolkit. If we would code in a lower level toolkit, the following code example could easily have dozens of lines.

   1  #!/usr/bin/python
   2 
   3  # simple.py
   4 
   5  import sys
   6  from PyQt4 import QtGui
   7 
   8  app = QtGui.QApplication(sys.argv)
   9 
  10  widget = QtGui.QWidget()
  11  widget.resize(250, 150)
  12  widget.setWindowTitle('simple')
  13  widget.show()
  14 
  15  sys.exit(app.exec_())

   1  import sys
   2  from PyQt4 import QtGui

Here we provide the necessary imports. The basic GUI widgets are located in QtGui module.

app = QtGui.QApplication(sys.argv)

Every PyQt4 application must create an application object. The application object is located in the QtGui module. The sys.argv parameter is a list of arguments from the command line. Python scripts can be run from the shell. It is a way, how we can control the startup of our scripts.

 widget = QtGui.QWidget()

The QWidget widget is the base class of all user interface objects in PyQt4. We provide the default constructor for QWidget. The default constructor has no parent. A widget with no parent is called a window.

 widget.resize(250, 150)

The resize() method resizes the widget. It is 250px wide and 150px high.

 widget.setWindowTitle('simple')

Here we set the title for our window. The title is shown in the titlebar.

 widget.show()

The show() method displays the widget on the screen.

 sys.exit(app.exec_())

Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends, if we call the exit() method or the main widget is destroyed. The sys.exit() method ensures a clean exit. The environment will be informed, how the application ended.

You wonder why the exec_() method has the underscore? Everything has a meaning. This is obviously because the exec is a python keyword. And thus, exec_() was used instead.

simple.jpg Figure: Simple

1.2. An application icon 程序图标

The application icon is a small image, which is usually displayed in the top left corner of the titlebar. In the following example we will show, how we do it in PyQt4. We will also introduce some new methods.

   1 #!/usr/bin/python
   2 
   3 # icon.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 
   8 
   9 class Icon(QtGui.QWidget):
  10     def __init__(self, parent=None):
  11         QtGui.QWidget.__init__(self, parent)
  12 
  13         self.setGeometry(300, 300, 250, 150)
  14         self.setWindowTitle('Icon')
  15         self.setWindowIcon(QtGui.QIcon('icons/web.png'))
  16 
  17 
  18 app = QtGui.QApplication(sys.argv)
  19 icon = Icon()
  20 icon.show()
  21 sys.exit(app.exec_())

The previous example was coded in a procedural style. Python programming language supports both procedural and object oriented programming styles. Programming in PyQt4 means programming in OOP.

 class Icon(QtGui.QWidget):
     def __init__(self, parent=None):
         QtGui.QWidget.__init__(self, parent)

The three most important things in object oriented programming are classes, data and methods. Here we create a new class called Icon. The Icon class inherits from QtGui.QWidget class. This means, that we must call two constructors. The first one for the Icon class and the second one for the inherited class.

 self.setGeometry(300, 300, 250, 150)
 self.setWindowTitle('Icon')
 self.setWindowIcon(QtGui.QIcon('icons/web.png'))

All three classes have been inherited from the QtGui.QWidget class. The setGeometry() does two things. It locates the window on the screen and sets the size of the window. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. The last method sets the application icon. To do this, we have created a QIcon object. The QIcon receives the path to our icon to be displayed.

icon.jpg Figure: Icon

1.3. Showing a tooltip 显示浮动提示

We can provide a balloon help for any of our widgets.

   1 #!/usr/bin/python
   2 
   3 # tooltip.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 from PyQt4 import QtCore
   8 
   9 
  10 class Tooltip(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('Tooltip')
  16 
  17         self.setToolTip('This is a <b>QWidget</b> widget')
  18         QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))
  19 
  20 
  21 app = QtGui.QApplication(sys.argv)
  22 tooltip = Tooltip()
  23 tooltip.show()
  24 app.exec_()

In this example, we show a tooltip for a QWidget widget.

 self.setToolTip('This is a <b>QWidget</b> widget')

To create a tooltip, we call the setTooltip() method. We can use rich text formatting.

 QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))

Because the default QToolTip font looks bad, we change it.

tooltip.jpg Figure: Tooltip

1.4. Closing a window 关闭窗口

关闭窗口 The obvious way to how to close a window is to click on the x mark on the titlebar. In the next example, we will show, how we can programatically close our window. We will briefly touch signals and slots.

The following is the constructor of a QPushButton, that we will use in our example.

   QPushButton(string text, QWidget parent = None)

The text parameter is a text that will be displayed on the button. The parent is the ancestor, onto which we place our button. In our case it is QWidget.

   1 #!/usr/bin/python
   2 
   3 # quitbutton.py
   4 
   5 import sys
   6 from PyQt4 import QtGui, QtCore
   7 
   8 
   9 class QuitButton(QtGui.QWidget):
  10     def __init__(self, parent=None):
  11         QtGui.QWidget.__init__(self, parent)
  12 
  13         self.setGeometry(300, 300, 250, 150)
  14         self.setWindowTitle('Icon')
  15 
  16         quit = QtGui.QPushButton('Close', self)
  17         quit.setGeometry(10, 10, 60, 35)
  18 
  19         self.connect(quit, QtCore.SIGNAL('clicked()'),
  20             QtGui.qApp, QtCore.SLOT('quit()'))
  21 
  22 
  23 app = QtGui.QApplication(sys.argv)
  24 qb = QuitButton()
  25 qb.show()
  26 sys.exit(app.exec_())

   1  quit = QtGui.QPushButton('Close', self)
   2  quit.setGeometry(10, 10, 60, 35)

We create a push button and position it on the QWidget just like we have positioned the QWidget on the screen.

 self.connect(quit, QtCore.SIGNAL('clicked()'),
     QtGui.qApp, QtCore.SLOT('quit()'))

The event processing system in PyQt4 is built with the signal & slot mechanism. If we click on the button, the signal clicked() is emitted. The slot can be a PyQt slot or any python callable. The QtCore.QObject.connect() method connects signals with slots. In our case the slot is a predefined PyQt quit() slot. The communication is done between two objects. The sender and the receiver. The sender is the push button, the receiver is the application object.

quitbutton.jpg Figure: quit button

1.5. Message Box 对话框

By default, if we click on the x button on the titlebar, the QWidget is closed. Sometimes we want to modify this default behaviour. For example, if we have a file opened in an editor to which we did some changes. We show a message box to confirm the action.

   1 #!/usr/bin/python
   2 
   3 # messagebox.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 
   8 
   9 class MessageBox(QtGui.QWidget):
  10     def __init__(self, parent=None):
  11         QtGui.QWidget.__init__(self, parent)
  12 
  13         self.setGeometry(300, 300, 250, 150)
  14         self.setWindowTitle('message box')
  15 
  16 
  17     def closeEvent(self, event):
  18         reply = QtGui.QMessageBox.question(self, 'Message',
  19             "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  20 
  21         if reply == QtGui.QMessageBox.Yes:
  22             event.accept()
  23         else:
  24             event.ignore()
  25 
  26 app = QtGui.QApplication(sys.argv)
  27 qb = MessageBox()
  28 qb.show()
  29 sys.exit(app.exec_())

If we close the QWidget, the QCloseEvent is generated. To modify the widget behaviour we need to reimplement the closeEvent() event handler.

 reply = QtGui.QMessageBox.question(self, 'Message',
     "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

We show a message box with two buttons. Yes and No. The first string appears on the titlebar. The second string is the message text displayed by the dialog. The return value is stored in the reply variable.

 if reply == QtGui.QMessageBox.Yes:
     event.accept()
 else:
    event.ignore()

Here we test the return value. If we clicked Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwise we ignore the close event.

messagebox.jpg Figure: message box

1.6. Centering window on the screen 把窗口放在屏幕正中

The following script shows, how we can center a window on the desktop screen.

   1 #!/usr/bin/python
   2 
   3 # center.py
   4 
   5 import sys
   6 from PyQt4 import QtGui
   7 
   8 
   9 class Center(QtGui.QWidget):
  10     def __init__(self, parent=None):
  11         QtGui.QWidget.__init__(self, parent)
  12 
  13         self.setWindowTitle('center')
  14         self.resize(250, 150)
  15         self.center()
  16 
  17     def center(self):
  18         screen = QtGui.QDesktopWidget().screenGeometry()
  19         size =  self.geometry()
  20         self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
  21 
  22 
  23 app = QtGui.QApplication(sys.argv)
  24 qb = Center()
  25 qb.show()
  26 sys.exit(app.exec_())

 self.resize(250, 150)

Here we resize the QWidget to be 250px wide and 150px heigh.

 screen = QtGui.QDesktopWidget().screenGeometry()

We figure out the screen resolution of our monitor.

 size =  self.geometry()

Here we get the size of our QWidget.

 self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

Here we move the window to the center of the screen.

First_Programs_第一个程序 (last edited 2010-11-16 01:14:04 by zhuyj)