PySide學習教程_第1頁
PySide學習教程_第2頁
PySide學習教程_第3頁
PySide學習教程_第4頁
PySide學習教程_第5頁
已閱讀5頁,還剩140頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、PySide tutorialThis is PySide tutorial. The tutorial is suited for beginners and intermediate programmers. After reading this tutorial, you will be able to program nontrivial PySide applications.Table of contents HYPERLINK /gui/pysidetutorial/introduction/ Introduction HYPERLINK /gui/pysidetutorial/

2、firstprograms/ First programs HYPERLINK /gui/pysidetutorial/menusandtoolbars/ Menus and toolbars HYPERLINK /gui/pysidetutorial/layoutmanagement/ Layout management HYPERLINK /gui/pysidetutorial/eventsandsignals/ Events and signals HYPERLINK /gui/pysidetutorial/dialogs/ Dialogs HYPERLINK /gui/pysidetu

3、torial/widgets/ Widgets HYPERLINK /gui/pysidetutorial/widgets2/ Widgets II HYPERLINK /gui/pysidetutorial/dragdrop/ Drag & drop HYPERLINK /gui/pysidetutorial/drawing/ Drawing HYPERLINK /gui/pysidetutorial/customwidgets/ Custom widgets HYPERLINK /gui/pysidetutorial/thetetrisgame/ The Tetris gamePySide

4、PySide is Python library to create cross-platform graphical user interfaces. It is a Python binding to the Qt framework. Qt library is one of the most powerful GUI libraries. It is developed by Digia and Qt Project. HYPERLINK /share TweetRelated tutorialsThere is a full HYPERLINK /lang/python/ Pytho

5、n tutorialon ZetCode. Tutorials for other GUI Python bindings include HYPERLINK /gui/pyqt4/ PyQt4 tutorial, HYPERLINK /wxpython/ wxPython tutorial, HYPERLINK /gui/pygtk/ PyGTK tutorialand HYPERLINK /gui/tkinter/ Tkinter tutorial.Introduction to PySide toolkitThis is an introductory PySide tutorial.

6、The purpose of this tutorial is to get you started with the PySide toolkit. The tutorial has been created and tested on Linux.About PySidePySide is Python library to create cross-platform graphical user interfaces. It is a Python binding to the Qt framework. Qt library is one of the most powerful GU

7、I libraries. The official home site for PySide is HYPERLINK /wiki/PySide /wiki/PySide. The installation instructions can be found at HYPERLINK /pypi/PySide /pypi/PySide.PySide is implemented as a set of Python modules. Currently it has 15 modules. These modules provide powerful tools to work with GU

8、I, multimedia, XML documents, network or databases. In our tutorial, we will work with two of these modules. TheQtGuiand theQtCoremodules.TheQtCoremodule contains the core non GUI functionality. This module is used for working with time, files and directories, various data types, streams, URLs, mime

9、 types, threads or processes. TheQtGuimodule contains the graphical components and related classes. These include for example buttons, windows, status bars, toolbars, sliders, bitmaps, colours, fonts etc.PySide has been released after Nokia, the owner of the Qt toolkit, failed to reach an agreement

10、with Riverbank Computing to include the LGPL as an alternative license. PySide has a high API compatibility wit PyQt4, so migrating to PySide is not difficult.PythonPython is a general-purpose, dynamic, object-oriented programming language. The design purpose of the Python language emphasizes progra

11、mmer productivity and code readability. Python was initially developed byGuido van Rossum. It was first released in 1991. Python was inspired by ABC, Haskell, Java, Lisp, Icon and Perl programming languages. Python is a high level, general purpose, multiplatform, interpreted language. Python is a mi

12、nimalistic language. One of its most visible features is that it does not use semicolons nor brackets. Python uses indentation instead. There are two main branches of Python currently. Python 2.x and Python 3.x. Python 3.x breaks backward compatibility with previous releases of Python. It was create

13、d to correct some design flaws of the language and make the language more clean. The most recent version of Python 2.x is 2.7.1, and of Python 3.x 3.1.3. This tutorial covers Python 2.x versions. Most of the code is written in Python 2.x versions. It will take some time till the software base and pr

14、ogrammers will migrate to Python 3.x. Today, Python is maintained by a large group of volunteers worldwide. Python is open source software.Python is an ideal start for those, who want to learn programming.Python programming language supports several programming styles. It does not force a programmer

15、 to a specific paradigm. Python supports object oriented and procedural programming. There is also a limited support for functional programming.The official web site for the Python programming language is HYPERLINK / Python ranks among the most popular programming languages. According to the HYPERLI

16、NK / , Python ranks on the 6. place. The HYPERLINK /index.php/content/paperinfo/tpci/index.html TIOBE indexputs Python on the 8. place. On HYPERLINK /languages , a popular repository of software projects, Python is the third most popular language, having 9% share of all projects hosted.Python toolki

17、tsFor creating modern graphical user interfaces, Python programmers can choose among these decent options: PySide, PyQt4, Python/Gnome (former PyGTK) and wxPython.This chapter was an introduction to PySide toolkit.First programs in PySideIn this part of the PySide tutorial we will learn some basic f

18、unctionality.Simple exampleThe code example is very simplistic. It only shows a small window. Yet we can do a lot with this window. We can resize it, maximise it or minimise it. This requires a lot of coding. Someone already coded this functionality. Because it repeats in most applications, there is

19、 no need to code it over again. So it has been hidden from a programmer. PySide 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# -*- coding: utf-8 -*-# simple.pyimport sysfrom PySide import QtGuiapp =

20、QtGui.QApplication(sys.argv)wid = QtGui.QWidget()wid.resize(250, 150)wid.setWindowTitle(Simple)wid.show()sys.exit(app.exec_()The above code shows a small window on the screen.import sysfrom PySide import QtGuiHere we provide the necessary imports. The basic GUI widgets are located inQtGuimodule.app

21、= QtGui.QApplication(sys.argv)Every PySide application must create an application object. The application object is located in the QtGui module. Thesys.argvparameter 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

22、 our scripts.wid = QtGui.QWidget()TheQWidgetwidget is the base class of all user interface objects in PySide. We provide the default constructor forQWidget. The default constructor has no parent. A widget with no parent is called a window.wid.resize(250, 150)Theresize()method resizes the widget. It

23、is 250px wide and 150px high.wid.setWindowTitle(Simple)Here we set the title for our window. The title is shown in the titlebar.wid.show()Theshow()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

24、. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends if we call theexit()method or the main widget is destroyed. Thesys.exit()method ensures a clean exit. The environment will be informed, how the application ended.You wonder why the

25、exec_()method has an underscore? Everything has a meaning. This is obviously because theexecis a Python keyword. And thus,exec_()was used instead.Figure: SimpleAn application iconThe application icon is a small image, which is usually displayed in the top left corner of the titlebar. It is also visi

26、ble in the taskbar. In the following example we will show, how we do it in PySide. We will also introduce some new methods.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tutorial This example shows an iconin the titlebar of the window.author: Jan Bodnarwebsite: last edited: August 2011import

27、 sysfrom PySide import QtGuiclass Example(QtGui.QWidget): def _init_(self): super(Example, self)._init_() self.initUI() def initUI(self): self.setGeometry(300, 300, 250, 150) self.setWindowTitle(Icon) self.setWindowIcon(QtGui.QIcon(web.png) self.show() def main(): app = QtGui.QApplication(sys.argv)

28、ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()The previous example was coded in a procedural style. Python programming language supports both procedural and object oriented programming styles. Programming in PySide means programming in OOP.class Example(QtGui.QWidget): def _init_(self

29、): super(Example, self)._init_()The three most important things in object oriented programming are classes, data and methods. Here we create a new class called Example. The Example class inherits fromQtGui.QWidgetclass. This means that we must call two constructors. The first one for the Example cla

30、ss and the second one for the inherited class. The second one is called with thesuper()method.self.setGeometry(300, 300, 250, 150)self.setWindowTitle(Icon)self.setWindowIcon(QtGui.QIcon(web.png) All three methods have been inherited from theQtGui.QWidgetclass. ThesetGeometry()does two things. It loc

31、ates 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 aQtGui.QIconobject. TheQtGui.QIco

32、nreceives the path to our icon to be displayed.def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()We put the startup code inside themain()method. This is a Python idiom.Figure: IconAn icon is visible in the top-left corner of the window.Showin

33、g a tooltipWe can provide a balloon help for any of our widgets.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tutorial This example shows a tooltip on a window and a buttonauthor: Jan Bodnarwebsite: last edited: August 2011import sysfrom PySide import QtGuiclass Example(QtGui.QWidget): def

34、_init_(self): super(Example, self)._init_() self.initUI() def initUI(self): QtGui.QToolTip.setFont(QtGui.QFont(SansSerif, 10) self.setToolTip(This is a QWidget widget) btn = QtGui.QPushButton(Button, self) btn.setToolTip(This is a QPushButton widget) btn.resize(btn.sizeHint() btn.move(50, 50) self.s

35、etGeometry(300, 300, 250, 150) self.setWindowTitle(Tooltips) self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()In this example, we show a tooltip for a two PySide widgets.QtGui.QToolTip.setFont(QtGui.QFont(SansSerif, 10)This stati

36、c method sets a font used to render tooltips. We use a 10px SansSerif font.self.setToolTip(This is a QWidget widget)To create a tooltip, we call thesetTooltip()method. We can use rich text formatting.btn = QtGui.QPushButton(Button, self)btn.setToolTip(This is a QPushButton widget)We create a button

37、widget and set a tooltip for it.btn.resize(btn.sizeHint()btn.move(50, 50) The button is being resized and moved on the window. ThesizeHint()method gives a recommended size for the button.Figure: TooltipsClosing a windowThe obvious way how to close a window is to click on the x mark on the titlebar.

38、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 aQtGui.QPushButton, that we will use in our example.class PySide.QtGui.QPushButton(text, parent=None)Thetextparameter is a text that will be dis

39、played on the button. Theparentis the widget, onto which we place our button. In our case it will be aQtGui.QWidget.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tutorial This program creates a quitbutton. When we press the button,the application terminates. author: Jan Bodnarwebsite: last

40、edited: August 2011import sysfrom PySide import QtGui, QtCoreclass Example(QtGui.QWidget): def _init_(self): super(Example, self)._init_() self.initUI() def initUI(self): qbtn = QtGui.QPushButton(Quit, self) qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit) qbtn.resize(qbtn.sizeHint() qb

41、tn.move(50, 50) self.setGeometry(300, 300, 250, 150) self.setWindowTitle(Quit button) self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()In this example, we create a quit button. Upon clicking on the window, the application termina

42、tes.qbtn = QtGui.QPushButton(Quit, self)We create a push button. The button is an instance of theQtGui.QPushButtonclass. The first parameter of the constructor is the label of the button. The second parameter is the parent widget. The parent widget is the Example widget, which is aQtGui.QWidgetby in

43、heritance.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)The event processing system in PySide is built with the signal & slot mechanism. If we click on the button, the signalclickedis emitted. The slot can be a Qt slot or any Python callable. TheQtCore.QCoreApplicationcontains the mai

44、n event loop. It processes and dispatches all events. Theinstance()method gives us the current instance. Note thatQtCore.QCoreApplicationis created with theQtGui.QApplication. The clicked signal is connected to thequit()method, which terminates the application. The communication is done between two

45、objects. The sender and the receiver. The sender is the push button, the receiver is the application object.Figure: Quit buttonMessage BoxBy default, if we click on the x button on the titlebar, theQtGui.QWidgetis closed. Sometimes we want to modify this default behavior. For example, if we have a f

46、ile opened in an editor to which we did some changes. We show a message box to confirm the action.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tutorial This program shows a confirmation message box when we click on the closebutton of the application window. author: Jan Bodnarwebsite: last

47、edited: August 2011import sysfrom PySide import QtGuiclass Example(QtGui.QWidget): def _init_(self): super(Example, self)._init_() self.initUI() def initUI(self): self.setGeometry(300, 300, 250, 150) self.setWindowTitle(Message box) self.show() def closeEvent(self, event): reply = QtGui.QMessageBox.

48、question(self, Message, Are you sure to quit?, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply = QtGui.QMessageBox.Yes: event.accept() else: event.ignore() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()If we c

49、lose theQtGui.QWidget, theQCloseEventis generated. To modify the widget behaviour we need to reimplement thecloseEvent()event handler.reply = QtGui.QMessageBox.question(self, Message, Are you sure to quit?, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)We show a message box with

50、 two buttons. Yes and No. The first string appears on the titlebar. The second string is the message text displayed by the dialog. The third argument specifies the combination of buttons appearing in the dialog. The last parameter is the default button. It is the button, which has initially the keyb

51、oard focus. 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 click the Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwi

52、se we ignore the close event.Figure: Message boxCentering window on the screenThe following script shows, how we can center a window on the desktop screen.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tutorial This program centers a window on the screen. author: Jan Bodnarwebsite: last edit

53、ed: August 2011import sysfrom PySide import QtGuiclass Example(QtGui.QWidget): def _init_(self): super(Example, self)._init_() self.initUI() def initUI(self): self.resize(250, 150) self.center() self.setWindowTitle(Center) self.show() def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWi

54、dget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()Centering a window on the screen.self.center()The code that will center the window is placed in the custom center()

55、 method.qr = self.frameGeometry()We get a rectangle specifying the geometry of the main window. This includes any window frame.cp = QtGui.QDesktopWidget().availableGeometry().center()We figure out the screen resolution of our monitor. And from this resolution, we get the center point.qr.moveCenter(c

56、p)Our rectangle has already its width and height. Now we set the center of the rectangle to the center of the screen. The rectangles size is unchanged.self.move(qr.topLeft()We move the top-left point of the application window to the top-left point of the qr rectangle, thus centering the window on ou

57、r screen.In this part of the PySide tutorial, we covered some basics.Menus and toolbars in PySideIn this part of the PySide tutorial, we will create menus and toolbars. A menu is a group of commands located in a menubar. A toolbar has buttons with the common commands in the application.Main WindowTh

58、eQtGui.QMainWindowclass provides a main application window. This enables to create the classic application skeleton with a statusbar, toolbar(s) and a menubar.StatusbarThe statusbar is a widget that is used for displaying status information.#!/usr/bin/python# -*- coding: utf-8 -*-ZetCode PySide tuto

59、rial This program creates a statusbar.author: Jan Bodnarwebsite: last edited: August 2011import sysfrom PySide import QtGuiclass Example(QtGui.QMainWindow): def _init_(self): super(Example, self)._init_() self.initUI() def initUI(self): self.statusBar().showMessage(Ready) self.setGeometry(300, 300,

60、250, 150) self.setWindowTitle(Statusbar) self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()if _name_ = _main_: main()A statusbar is created with the help of theQtGui.QMainWindowwidget.self.statusBar().showMessage(Ready)To get the statusbar, we call thestat

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論