PySide学习教程.docx

上传人:b****7 文档编号:8748079 上传时间:2023-02-01 格式:DOCX 页数:132 大小:815.92KB
下载 相关 举报
PySide学习教程.docx_第1页
第1页 / 共132页
PySide学习教程.docx_第2页
第2页 / 共132页
PySide学习教程.docx_第3页
第3页 / 共132页
PySide学习教程.docx_第4页
第4页 / 共132页
PySide学习教程.docx_第5页
第5页 / 共132页
点击查看更多>>
下载资源
资源描述

PySide学习教程.docx

《PySide学习教程.docx》由会员分享,可在线阅读,更多相关《PySide学习教程.docx(132页珍藏版)》请在冰豆网上搜索。

PySide学习教程.docx

PySide学习教程

PySide学习教程

PySidetutorial

ThisisPySidetutorial.Thetutorialissuitedforbeginnersandintermediateprogrammers.Afterreadingthistutorial,youwillbeabletoprogramnontrivialPySideapplications.

Tableofcontents

∙Introduction

∙Firstprograms

∙Menusandtoolbars

∙Layoutmanagement

∙Eventsandsignals

∙Dialogs

∙Widgets

∙WidgetsII

∙Drag&drop

∙Drawing

∙Customwidgets

∙TheTetrisgame

PySide

PySideisPythonlibrarytocreatecross-platformgraphicaluserinterfaces.ItisaPythonbindingtotheQtframework.QtlibraryisoneofthemostpowerfulGUIlibraries.ItisdevelopedbyDigiaandQtProject.

Tweet

Relatedtutorials

Thereisafull Pythontutorial onZetCode.TutorialsforotherGUIPythonbindingsinclude PyQt4tutorial, wxPythontutorial, PyGTKtutorial and Tkintertutorial.

IntroductiontoPySidetoolkit

ThisisanintroductoryPySidetutorial.ThepurposeofthistutorialistogetyoustartedwiththePySidetoolkit.ThetutorialhasbeencreatedandtestedonLinux.

AboutPySide

PySideisPythonlibrarytocreatecross-platformgraphicaluserinterfaces.ItisaPythonbindingtotheQtframework.QtlibraryisoneofthemostpowerfulGUIlibraries.TheofficialhomesiteforPySideis qt-project.org/wiki/PySide.Theinstallationinstructionscanbefoundatpypi.python.org/pypi/PySide.

PySideisimplementedasasetofPythonmodules.Currentlyithas15modules.ThesemodulesprovidepowerfultoolstoworkwithGUI,multimedia,XMLdocuments,networkordatabases.Inourtutorial,wewillworkwithtwoofthesemodules.The QtGui andthe QtCore modules.

The QtCore modulecontainsthecorenonGUIfunctionality.Thismoduleisusedforworkingwithtime,filesanddirectories,variousdatatypes,streams,URLs,mimetypes,threadsorprocesses.The QtGui modulecontainsthegraphicalcomponentsandrelatedclasses.Theseincludeforexamplebuttons,windows,statusbars,toolbars,sliders,bitmaps,colours,fontsetc.

PySidehasbeenreleasedafterNokia,theowneroftheQttoolkit,failedtoreachanagreementwithRiverbankComputingtoinclude

#-*-coding:

utf-8-*-

#simple.py

importsys

fromPySideimportQtGui

app=QtGui.QApplication(sys.argv)

wid=QtGui.QWidget()

wid.resize(250,150)

wid.setWindowTitle('Simple')

wid.show()

sys.exit(app.exec_())

Theabovecodeshowsasmallwindowonthescreen.

importsys

fromPySideimportQtGui

Hereweprovidethenecessaryimports.ThebasicGUIwidgetsarelocatedin QtGui module.

app=QtGui.QApplication(sys.argv)

EveryPySideapplicationmustcreateanapplicationobject.TheapplicationobjectislocatedintheQtGuimodule.The sys.argv parameterisalistofargumentsfromthecommandline.Pythonscriptscanberunfromtheshell.Itisaway,howwecancontrolthestartupofourscripts.

wid=QtGui.QWidget()

The QWidget widgetisthebaseclassofalluserinterfaceobjectsinPySide.Weprovidethedefaultconstructorfor QWidget.Thedefaultconstructorhasnoparent.Awidgetwithnoparentiscalledawindow.

wid.resize(250,150)

The resize() methodresizesthewidget.Itis250pxwideand150pxhigh.

wid.setWindowTitle('Simple')

Herewesetthetitleforourwindow.Thetitleisshowninthetitlebar.

wid.show()

The show() methoddisplaysthewidgetonthescreen.

sys.exit(app.exec_())

Finally,weenterthemainloopoftheapplication.Theeventhandlingstartsfromthispoint.Themainloopreceiveseventsfromthewindowsystemanddispatchesthemtotheapplicationwidgets.Themainloopendsifwecallthe exit() methodorthemainwidgetisdestroyed.The sys.exit()methodensuresacleanexit.Theenvironmentwillbeinformed,howtheapplicationended.

Youwonderwhythe exec_() methodhasanunderscore?

Everythinghasameaning.Thisisobviouslybecausethe exec isaPythonkeyword.Andthus, exec_() wasusedinstead.

Figure:

Simple

Anapplicationicon

Theapplicationiconisasmallimage,whichisusuallydisplayedinthetopleftcornerofthetitlebar.Itisalsovisibleinthetaskbar.Inthefollowingexamplewewillshow,howwedoitinPySide.Wewillalsointroducesomenewmethods.

#!

/usr/bin/python

#-*-coding:

utf-8-*-

"""

ZetCodePySidetutorial

Thisexampleshowsanicon

inthetitlebarofthewindow.

author:

JanBodnar

website:

lastedited:

August2011

"""

importsys

fromPySideimportQtGui

classExample(QtGui.QWidget):

def__init__(self):

super(Example,self).__init__()

self.initUI()

definitUI(self):

self.setGeometry(300,300,250,150)

self.setWindowTitle('Icon')

self.setWindowIcon(QtGui.QIcon('web.png'))

self.show()

defmain():

app=QtGui.QApplication(sys.argv)

ex=Example()

sys.exit(app.exec_())

 

if__name__=='__main__':

main()

Thepreviousexamplewascodedinaproceduralstyle.Pythonprogramminglanguagesupportsbothproceduralandobjectorientedprogrammingstyles.ProgramminginPySidemeansprogramminginOOP.

classExample(QtGui.QWidget):

def__init__(self):

super(Example,self).__init__()

Thethreemostimportantthingsinobjectorientedprogrammingareclasses,dataandmethods.HerewecreateanewclasscalledExample.TheExampleclassinheritsfrom QtGui.QWidget class.Thismeansthatwemustcalltwoconstructors.ThefirstonefortheExampleclassandthesecondonefortheinheritedclass.Thesecondoneiscalledwiththe super() method.

self.setGeometry(300,300,250,150)

self.setWindowTitle('Icon')

self.setWindowIcon(QtGui.QIcon('web.png'))

Allthreemethodshavebeeninheritedfromthe QtGui.QWidget class.The setGeometry() doestwothings.Itlocatesthewindowonthescreenandsetsthesizeofthewindow.Thefirsttwoparametersarethexandypositionsofthewindow.Thethirdisthewidthandthefourthistheheightofthewindow.Thelastmethodsetstheapplicationicon.Todothis,wehavecreateda QtGui.QIcon object.The QtGui.QIcon receivesthepathtoouricontobedisplayed.

defmain():

app=QtGui.QApplication(sys.argv)

ex=Example()

sys.exit(app.exec_())

 

if__name__=='__main__':

main()

Weputthestartupcodeinsidethe main() method.ThisisaPythonidiom.

Figure:

Icon

Aniconisvisibleinthetop-leftcornerofthewindow.

Showingatooltip

Wecanprovideaballoonhelpforanyofourwidgets.

#!

/usr/bin/python

#-*-coding:

utf-8-*-

"""

ZetCodePySidetutorial

Thisexampleshowsatooltipon

awindowandabutton

author:

JanBodnar

website:

lastedited:

August2011

"""

importsys

fromPySideimportQtGui

classExample(QtGui.QWidget):

def__init__(self):

super(Example,self).__init__()

self.initUI()

definitUI(self):

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

self.setToolTip('ThisisaQWidgetwidget')

btn=QtGui.QPushButton('Button',self)

btn.setToolTip('ThisisaQPushButtonwidget')

btn.resize(btn.sizeHint())

btn.move(50,50)

self.setGeometry(300,300,250,150)

self.setWindowTitle('Tooltips')

self.show()

defmain():

app=QtGui.QApplication(sys.argv)

ex=Example()

sys.exit(app.exec_())

 

if__name__=='__main__':

main()

Inthisexample,weshowatooltipforatwoPySidewidgets.

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

Thisstaticmethodsetsafontusedtorendertooltips.Weusea10pxSansSeriffont.

self.setToolTip('ThisisaQWidgetwidget')

Tocreateatooltip,wecallthe setTooltip() method.Wecanuserichtextformatting.

btn=QtGui.QPushButton('Button',self)

btn.setToolTip('ThisisaQPushButtonwidget')

Wecreateabuttonwidgetandsetatooltipforit.

btn.resize(btn.sizeHint())

btn.move(50,50)

Thebuttonisbeingresizedandmovedonthewindow.The sizeHint() methodgivesarecommendedsizeforthebutton.

Figure:

Tooltips

Closingawindow

Theobviouswayhowtocloseawindowistoclickonthexmarkonthetitlebar.Inthenextexample,wewillshow,howwecanprogramaticallycloseourwindow.Wewillbrieflytouchsignalsandslots.

Thefollowingistheconstructorofa QtGui.QPushButton,thatwewilluseinourexample.

classPySide.QtGui.QPushButton(text[,parent=None])

The text parameterisatextthatwillbedisplayedonthebutton.The parent isthewidget,ontowhichweplaceourbutton.Inourcaseitwillbea QtGui.QWidget.

#!

/usr/bin/python

#-*-coding:

utf-8-*-

"""

ZetCodePySidetutorial

Thisprogramcreatesaquit

button.Whenwepressthebutton,

theapplicationterminates.

author:

JanBodnar

website:

lastedited:

August2011

"""

importsys

fromPySideimportQtGui,QtCore

classExample(QtGui.QWidget):

def__init__(self):

super(Example,self).__init__()

self.initUI()

definitUI(self):

qbtn=QtGui.QPushButton('Quit',self)

qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)

qbtn.resize(qbtn.sizeHint())

qbtn.move(50,50)

self.setGeometry(300,300,250,150)

self.setWindowTitle('Quitbutton')

self.show()

defmain():

app=QtGui.QApplication(sys.argv)

ex=Example()

sys.exit(app.exec_())

 

if__name__=='__main__':

main()

Inthisexample,wecreateaquitbutton.Uponclickingonthewindow,theapplicationterminates.

qbtn=QtGui.QPushButton('Quit',self)

Wecreateapushbutton.Thebuttonisaninstanceofthe QtGui.QPushButton class.Thefirstparameteroftheconstructoristhelabelofthebutton.Thesecondparameteristheparentwidget.TheparentwidgetistheExamplewidget,whichisa QtGui.QWidget byinheritance.

qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)

TheeventprocessingsysteminPySideisbuiltwiththesignal&slotmechanism.Ifweclickonthebutton,thesignal clicked isemitted.Theslotcanb

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工作范文 > 其它

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1