PySide学习教程_计算机软件及应用_IT计算机_专业资料.pdf

上传人:奔*** 文档编号:89820143 上传时间:2023-05-13 格式:PDF 页数:143 大小:12.62MB
返回 下载 相关 举报
PySide学习教程_计算机软件及应用_IT计算机_专业资料.pdf_第1页
第1页 / 共143页
PySide学习教程_计算机软件及应用_IT计算机_专业资料.pdf_第2页
第2页 / 共143页
点击查看更多>>
资源描述

《PySide学习教程_计算机软件及应用_IT计算机_专业资料.pdf》由会员分享,可在线阅读,更多相关《PySide学习教程_计算机软件及应用_IT计算机_专业资料.pdf(143页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、PySide tutorialThis is PySide tutorial.The tutorial is suited for beginners and intermediateprogrammers.After reading this tutorial,you will be able to programnontrivial PySide applications.Table of contents Inlroduction First programs Menus and toolbars Layout management Events and signals Dialogs

2、Widgels Widgets H Drag&drop Drawing Custom widgets The Tetris gamePySidePySide is Python library to create cross-platform graphical user interfaces.Itis a Python binding to the Qt framework.Qt library is one of the mostpowerful GUI libraries.It is developed by Digia and Qt Project.TweetRelated tutor

3、ialsThere is a full Python tutorial on ZetCode.Tutorials for other GUI Pythonbindings include PyOt4 tutorial,wxPython tutorial,PyGTKtutorial and Tkinter tutorial.Introduction to PySide toolkitThis is an introductory PySide tutorial.The purpose of this tutorial is to getyou started with the PySide to

4、olkit.The tutorial has been created and testedon Linux.About PySidePySide is Python library to create cross-platform graphical user interfaces.Itis a Python binding to the Qt framework.Qt library is one of the mostpowerful GUI libraries.The official home site for PySideis ul-Droject.org/wiki/PySide.

5、The installation instructions can be foundatpyDi.python.org/pypi/PySide.PySide is implemented as a set of Python modules.Currently it has 15modules.These modules provide powerful tools to work with GUI,multimedia,XML documents,network or databases.In our tutorial,we will work with twoof these module

6、s.The QtGui and the QtCore modules.The QtCore module contains the core non GUI functionality.This module isused for working with time,files and directories,various data types,streams,URLs,mime types,threads or processes.The QtGui module contains thegraphical components and related classes.These incl

7、ude 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 toreach an agreement with Riverbank Computing to include the LG PL as analternative license.PySide has a high API compatibility wit PyQt4,som

8、igrating to PySide is not difficult.PythonPython is a general-purpose,dynamic,object-oriented programminglanguage.The design purpose of the Python language emphasizesprogrammer productivity and code readability.Python was initially developedby Guido van Rossum.It was first released in 1991.Python wa

9、s inspired byABC,Haskell,Java,Lisp,Icon and Perl programming languages.Python is ahigh level,general purpose,multiplatform,interpreted language.Python is aminimalistic language.One of its most visible features is that it does not usesemicolons nor brackets.Python uses indentation instead.There are t

10、wo mainbranches of Python currently.Python 2.x and Python 3.x.Python 3.x breaksbackward compatibility with previous releases of Python.It was created tocorrect 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.Th

11、istutorial covers Python 2.x versions.Most of the code is written in Python 2.xversions.It will take some time till the software base and programmers willmigrate to Python 3.x.Today,Python is maintained by a large group ofvolunteers worldwide.Python is open source software.Python is an ideal start f

12、or those,who want to learn programming.Python programming language supports several programming styles.It doesnot force a programmer to a specific paradigm.Python supports objectoriented and procedural programming.There is also a limited support forfunctional programming.The official web site for th

13、e Python programming language is python.ergPython ranks among the most popular programming languages.According tothe .Python ranks on the 6.place.The TIOBE index puts Pythonon the 8.place.On 、a popular repository of software projects,Python is the third most popular language,having 9%share of all pr

14、ojectshosted.Python toolkitsFor creating modern graphical user interfaces,Python programmers canchoose among these decent options:PySide,PyQt4,Python/Gnome(formerPyGTK)and wxPython.This chapter was an introduction to PySide toolkit.First programs in PySideIn this part of the PySide tutorial we will

15、learn some basic functionality.Simple exampleThe code example is very simplistic.It only shows a small window.Yet we cando a lot with this window.We can resize it,maximise it or minimise it.Thisrequires a lot of coding.Someone already coded this functionality.Because itrepeats in most applications,t

16、here is no need to code it over again.So it hasbeen hidden from a programmer.PySide is a high level toolkit.If we wouldcode in a lower level toolkit,the following code example could easily havedozens of lines.#!/usr/bin/python#coding:utf-8#simple.pyimport sysfrom PySide import QtGuiapp=QtGui.QApplic

17、ation(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 locatedin QtGui module.app=QtGui.QApplicati

18、on(sys.argv)Every PySide application must create an application object.The applicationobject is located in the QtGui module.The sys.argv parameter is a list ofarguments 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.wid=QtGui.

19、QWidget()The QWidget widget is the base class of all user interface objects in PySide.Weprovide the default constructor for QWidget.The default constructor has noparent.A widget with no parent is called a window.wid.resize(250z 150)The resize()method resizes the widget.It is 250px wide and 150px hig

20、h.wid.setWindowTitle(*Simple 1)Here we set the title for our window.The title is shown in the titlebar.wid.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 startsfrom this point.The mainloop receives even

21、ts from the window system anddispatches them to the application widgets.The mainloop ends if we callthe exit()method or the main widget is destroyed.The sys.exit()methodensures a clean exit.The environment will be informed,how the applicationended.You wonder why the exec_()method has an underscore?E

22、verything has ameaning.This is obviously because the exec is a Python keyword.Andthus,exec_()was used instead.Figure:SimpleAn application iconThe application icon is a small image,which is usually displayed in the top leftcorner of the titlebar.It is also visible in the taskbar.In the following exam

23、plewe will show,how we do it in PySide.We will also introduce some newmethods.#!/usr/bin/python#coding:utf-8n n nZetCode PySide tutorialThis example shows an iconin the titlebar of the window.author:Jan Bodnarwebsite:last edited:August 2011H”nimport sysfrom PySide import QtGuiclass Example(QtGui.QWi

24、dget):def _init_(self):super(Example,self)._init_()self.initUI()def initUI(self):self.setGeometry(300,300,250,150)self.setWindowTitle(*Icon)self.setwindowicon(QtGui.Qlcon(1 web.png*)self.show()def main():app=QtGui.QApplication(sys.argv)ex=Example()sys.exit(app.exec_()if _name_ =*_main_:main()The pre

25、vious example was coded in a procedural style.Python programminglanguage supports both procedural and object oriented programming styles.Programming in PySide means programming in OOP.class Example(QtGui.QWidget):def _init_(self):super(Example,self)._init_()The three most important things in object

26、oriented programming are classes,data and methods.Here we create a new class called Example.The Exampleclass inherits from QtGui.QWidget class.This means that we must call twoconstructors.The first one for the Example class and the second one for theinherited class.The second one is called with the

27、super()method.self.setGeometry(300 z 300,250,150)self.setWindowTitle(11con1)self.setWindowlcon(QtGui.Qlcon(*web.png*)All three methods have been inherited from the QtGui.QWidget class.The setGeometry()does two things.It locates the window on the screen andsets the size of the window.The first two pa

28、rameters are the x and y positionsof the window.The third is the width and the fourth is the height of thewindow.The last method sets the application icon.To do this,we have createda QtGui.Qlcon object.The QtGui.Qlcon receives the path to our icon to bedisplayed.d ef m ain():app=Q tG ui.Q A p p lic

29、a tio n(sy s.argv)ex=Exam ple()sys.e x it(a p p.exec_()i f _ name_ =*_ main_:main()We put the startup code inside the main()method.This is a Python idiom.Figure:IconAn icon is visible in the top-left corner of the window.Showing a tooltipWe can provide a balloon help for any of our widgets.#!/u sr/b

30、 in/p y th o n#c o d in g:u tf-8iv n ifZetCode PySide tu to r ia lT his exam ple shows a to o ltip ona window and a b u tto na u th o r:Jan Bodnarw e b site:z e tc o d la s t e d ite d:A ugust 2011im port sysfrom PySide im port QtGuiclass Example(QtGui.QWidget):def _init_(self):super(Example,self).i

31、nit()self.initUI()def initUI(self):QtGui.QToolTip.setFont(QtGui.QFont(f SansSerif1z 10)self.setToolTip(*This is a QWidget widget*)btn=QtGui.QPushButton(Button 1z self)btn.setTooITip(,This is a QPushButton widget!)btn.resize(btn.sizeHint()btn.move(50z 50)self.setGeometry(300,300,250,150)self.setWindo

32、wTitle(*Tooltips 1)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(SansSerifr 10)This static method sets a font used to render tooltips.We use a

33、 lOpx SansSeriffont.self.setToolTip(1 This is a QWidget widget1)To create a tooltip,we call the setTooltipO method.We can use rich textformatting.btn=QtGui.QPushButton(*Button*,self)btn.setToolTip(*This is a QPushButton widget)We create a button widget and set a tooltip for it.btn.resize(btn.sizeHin

34、t()btn.move(50z 50)The button is being resized and moved on the window.The sizeHint()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 thetitlebar.In the next example,we will show,how we can programaticall

35、y closeour window.We will briefly touch signals and slots.The following is the constructor of a QtGui.QPushButton,that we will use inour example.class PySide.QtGui.QPushButton(textr parent=None)The text parameter is a text that will be displayed on the button.The parent is the widget,onto which we p

36、lace our button.In our case it will bea QtGui.QWidget.#!/usr/bin/python#一*一 coding:utf-8 nZetCode PySide tutorialThis program creates a quitbutton.When we press the button,the application terminates.author:Jan Bodnarwebsite:last edited:August 2011I V V I Himport sysfrom PySide import QtGui,QtCorecla

37、ss Example(QtGui.QWidget):def _init_(self):super(Example,self),init()self.initUI()def initUI(self):qbtn=QtGui.QPushButton(uit,self)qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)qbtn.resize(qbtn.sizeHint()qbtn.move(50 f 50)self.setGeometry(300f 300,250,150)self.setWindowTitle(1 Quit bu

38、tton*)self.show()def main():app=QtGui.QApplication(sys.argv)ex=Example()sysexit(app.exec_()if _name_=*_main_f:main()In this example,we create a quit button.Upon clicking on the window,theapplication terminates.qbtn=QtGui.QPushButton(Quitf z self)We create a push button.The button is an instance ofth

39、e QtGui.QPushButton class.The first parameter of the constructor is thelabel of the button.The second parameter is the parent widget.The parentwidget is the Example widget,which is a QtGui.QWidget by inheritance.qbtn,clicked.connect(QtCore.QCoreApplication.instance().quit)The event processing system

40、 in PySide is built with the signal&slotmechanism.If we click on the button,the signal clicked is emitted.The slotcan be a Qt slot or any Python callable.TheQtCore.QCoreApplication containsthe main event loop.It processes and dispatches all events.Theinstance()method gives us the current instance.No

41、tethat QtCore.QCoreApp 1 ication is created with the QtGui.QApplication.Theclicked signal is connected to the quit()method,which terminates theapplication.The communication is done between two objects.The sender andthe receiver.The sender is the push button,the receiver is the applicationobject.Figu

42、re:Quit buttonMessage BoxBy default,if we click on the x button on the titlebar,the QtGui.QWidget isclosed.Sometimes we want to modify this default behavior.For example,if wehave a file opened in an editor to which we did some changes.We show amessage box to confirm the action.#!/usr/bin/python#codi

43、ng:utf-8IV fl IVZetCode PySide tutorialThis program shows a confirmationmessage box when we click on the closebutton of the application window.author:Jan Bodnarwebsite:last edited:August 2011n n nimport sysfrom PySide import QtGuiclass Example(QtGui.QWidget):def _init_(self):super(Example,self)._ini

44、t_()self.initUI()def initUI(self):self.setGeometry(300,300,250,150)self.setWindowTitle(Message box*)self.show()def closeEvent(selfz event):reply=QtGui.QMessageBox.question(self,*Message 1,Are you sure to quit?”,QtGui.QMessageBox.Yes IQtGui.QMessageBox.No,QtGui.QMessageBox.No)if reply=QtGui.QMessageB

45、ox.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 close the QtGui.QWidget,the QCloseEvent is generated.To modify thewidget behaviour we need to reimplement the closeEvent()event handler.reply=QtGui.QMessag

46、eBox.question(self,*Message,nAre you sure to quit?”,QtGui.QMessageBox.Yes|QtGui.QMessageBox.No,QtGui.QMessageBox.No)We show a message box with two buttons.Yes and No.The first string appearson the titlebar.The second string is the message text displayed by the dialog.The third argument specifies the

47、 combination of buttons appearing in thedialog.The last parameter is the default button.It is the button,which hasinitially the keyboard 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 th

48、e Yes button,we accept the eventwhich leads to the closure of the widget and to the termination of theapplication.Otherwise we ignore the close event.Figure:Message boxCentering window on the screenThe following script shows,how we can center a window on the desktopscreen.#!/usr/bin/python#coding:ut

49、f-8u nZetCode PySide tutorialThis program centers a windowon the screen.author:Jan Bodnarwebsite:last edited:August 2011n n nimport sysfrom PySide import QtGuiclass Example(QtGui.QWidget):def _init_(self):super(Example,self)._init_()self.initUI()def initUI(self):self.resize(250z 150)self.center()sel

50、f.setWindowTitle(Center1)self.show()def center(self):qr=self.frameGeometry()cp=QtGui.QDesktopWidget().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

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁