First programs in PyQt4 toolkit

来源:互联网 发布:北京联通网络测速 编辑:程序博客网 时间:2024/04/30 16:16

First programs in PyQt4 toolkit

In this part of the PyQt4 tutorial we will learn some basic functionality.

Simple example

The code example is very simplistic. It only shows a small window. Yet we can do a lotwith 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.

#!/usr/bin/python

# simple.py

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)

widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
widget.show()

sys.exit(app.exec_())

The above code shows a small window on the screen.

 import sys
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 an underscore? Everything has a meaning. This is obviously because the exec is a python keyword. And thus, exec_() was used instead.


Simple

Figure: Simple

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.

#!/usr/bin/python

# icon.py

import sys
from PyQt4 import QtGui


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

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


app = QtGui.QApplication(sys.argv)
icon = Icon()
icon.show()
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

Figure: Icon

Showing a tooltip

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

#!/usr/bin/python

# tooltip.py

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore


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

self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Tooltip')

self.setToolTip('This is a <b>QWidget</b> widget')
QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))


app = QtGui.QApplication(sys.argv)
tooltip = Tooltip()
tooltip.show()
sys.exit(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

Figure: Tooltip

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.

#!/usr/bin/python

# quitbutton.py

import sys
from PyQt4 import QtGui, QtCore


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

self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Quit button')

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

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


app = QtGui.QApplication(sys.argv)
qb = QuitButton()
qb.show()
sys.exit(app.exec_())
 quit = QtGui.QPushButton('Close', self)
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.


quit button

Figure: quit button

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.

#!/usr/bin/python

# messagebox.py

import sys
from PyQt4 import QtGui


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

self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('message box')


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

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

app = QtGui.QApplication(sys.argv)
qb = MessageBox()
qb.show()
sys.exit(app.exec_())

If we close the QWidget, the QCloseEvent is generated. To modify the widgetbehaviour 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.


message box

Figure: message box

Centering window on the screen

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

#!/usr/bin/python

# center.py

import sys
from PyQt4 import QtGui


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

self.setWindowTitle('center')
self.resize(250, 150)
self.center()

def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)


app = QtGui.QApplication(sys.argv)
qb = Center()
qb.show()
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.

 

 

In this part of the PyQt4 tutorial, we covered some basics.

 

原帖地址:http://zetcode.com/tutorials/pyqt4/firstprograms/

原创粉丝点击