原文: http://zetcode.com/gui/pyqt5/firstprograms/python
在這部分教程中咱們將學習PyQt5的一些基本功能web
這是一個只顯示一個小窗口的簡單示例。但咱們能夠對這個窗口進行一些操做,如調整尺寸,最大化或最小化。這須要編寫不少代碼,但有人已經完成了這個功能。由於它在多種程序中的通用性,因此再也不須要重複編碼。PyQt5是一個高級工具集。若是咱們使用較低級的工具集進行編碼,要實現這個功能最少也要上百行代碼。shell
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create a simple window in PyQt5. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__main__': app = QApplication(sys.argv) w = QWidget() w.resize(250, 150) w.move(300, 300) w.setWindowTitle('Simple') w.show() sys.exit(app.exec_())
上面的代碼會在屏幕上顯示一個小窗體。編程
import sys from PyQt5.QtWidgets import QApplication, QWidget
在這裏咱們導入了必要的模塊。這些基本控件位於PyQt5.QtWidgets模塊中。app
app = QApplication(sys.argv)
每一個PyQt5應用程序都須要建立一個application對象。sys.argv是從命令行傳入的參數列表。Python腳本能夠從shell中運行。這是一種控制腳本啓動的方式。編輯器
w = QWidget()
控件QWidget是QtPy5中全部UI對象的基類。咱們調用了QWidget的默認構造器。默認構造器沒有parent參數。沒有parent的控件稱爲窗體(window)。工具
w.resize(250, 150)
resize()方法用於設置控件的尺寸。它寬250px高150px。學習
w.move(300, 300)
move()方法將控件移動到座標爲x=300, y=300的位置字體
w.setWindowTitle('Simple')
這裏設置了窗體的標題。標題在標題欄中顯示。ui
w.show()
show()方法將控件顯示在屏幕上。控件要先在內存中建立,而後在屏幕上顯示。
sys.exit(app.exec_())
最後咱們進入了application的主循環。事件處理從這裏開始。主循環從窗體系統中接收事件,並將事件分發給控件。在調用exit()方法或主控件銷燬時主循環會中止。sys.exit()方法確保能夠乾淨地退出。系統能夠感知到程序是如何退出的。
注意exec_()
方法的下劃線。因爲exec是python中的關鍵字,因此使用exec_()。
程序的圖標是顯示在標題欄左上角的一個小圖像。接下來咱們將介紹如何用PyQt5實現,這會用到一些新的API。
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This example shows an icon in the titlebar of the window. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QIcon class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png')) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
以前的示例採用了過程式編碼風格。Python語言支持過程式與面向對象的編程風格。PyQt5採用了面向對象編程。
class Example(QWidget): def __init__(self): super().__init__() ...
在面向對象編程中有三個要素:類,數據與方法。咱們建立了一個Example
類,它繼承自QWidget
。這就意味着咱們要調用兩個構造器:首先是Example
類的,而後是被繼承的類的。super()
方法返回了Example
的父對象,而且咱們調用了它的構造器。__init__()
方法是Python語言中的構造器。
self.initUI()
GUI的建立交給了initUI()方法。
self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png'))
這三個方法繼承自QWidget
類。setGeometry()
設置了控件的位置與尺寸。前兩個參數是窗體的x,y座標,第三個與第四個參數設置了窗體的寬度與高度。實際上它合併了resize()
與move()
方法。最後一個方法設置了應用的圖標。咱們須要建立一個QIcon對象,QIcon
接受要顯示的圖標的路徑做爲參數。
if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
在這裏建立了application與example對象,而且啓動了主循環。
咱們能夠爲全部控件添加消息提示框。
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This example shows a tooltip on a window and a button. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication) from PyQt5.QtGui import QFont class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget') btn = QPushButton('Button', self) btn.setToolTip('This is a <b>QPushButton</b> widget') btn.resize(btn.sizeHint()) btn.move(50, 50) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Tooltips') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
在這個例子中咱們爲兩個PyQt5控件添加了提示消息。
QToolTip.setFont(QFont('SansSerif', 10))
這個靜態方法爲tooltip設置了10px的Sanserif字體。
self.setToolTip('This is a <b>QWidget</b> widget')
咱們調用setToolTip()
方法爲控件建立提示消息。消息可使用富文本格式。
btn = QPushButton('Button', self) btn.setToolTip('This is a <b>QPushButton</b> widget')
這裏咱們建立了一個PushButton併爲它設置了一個富文本提示消息。
btn.resize(btn.sizeHint()) btn.move(50, 50)
這裏設置了button的尺寸,並將其在窗體上移動。sizeHint()
方法爲控件返回一個推薦的尺寸。
關閉窗體最明顯的方法是點擊標題欄上的x
符號。在下面的例子中,我會展現如何經過編程來關閉窗體。這裏咱們要涉及到簡單的signal和slot(信號槽)。
QPushButton(string text, QWidget parent = None)
這是以前用到的QPushButton控件的構造器。其中text
參數是將要在按鈕上顯示的文本,parent
表示按鈕的父控件,在這個例子中就是QWidget。一個程序的全部控件構成了一個控件樹。在這個樹上大部分控件都有父控件。沒有父控件的控件是頂層窗體。
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This program creates a quit button. When we press the button, the application terminates. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import QWidget, QPushButton, QApplication from PyQt5.QtCore import QCoreApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): qbtn = QPushButton('Quit', self) qbtn.clicked.connect(QCoreApplication.instance().quit) qbtn.resize(qbtn.sizeHint()) qbtn.move(50, 50) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Quit button') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
在這個示例中咱們建立了一個退出按鈕。程序會在點擊了這個按鈕時退出。
from PyQt5.QtCore import QCoreApplication
這裏咱們我用到QtCore
模塊中的一個對象。
qbtn = QPushButton('Quit', self)
咱們建立了一個PushButton, 它是QPushButton
類的實例。構造器的第一個參數是按鈕的標籤,第二個參數是它的父控件,也就是Example
, 因爲繼承關係Example
也是QWidget
。
qbtn.clicked.connect(QCoreApplication.instance().quit)
PyQt5中的事件處理系統採用signal&slot(信號槽)機制。當咱們點擊按鈕時會發出clicked
信號。slot能夠是Qt slot或任何Python的callable對象。QCoreApplication
包含了主事件循環;它能夠處理並分發事件。instance()
方法返回它的當前實例。QCoreApplication
是由QApplication建立的。clicked信號鏈接到能夠退出程序的quit()方法。這個過程由兩個對象完成:發送者與接收者。發送者是PushButton,接收者是QApplication對象。
當咱們點擊標題欄上的x按鈕時默認會關閉QWidget。但有時咱們想改變這種默認行爲。例如,若是咱們在編輯器中打開了一個文件,而且對這個文件作了修改。在關閉前咱們但願顯示一個對話框讓用戶進行確認。
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This program shows a confirmation message box when we click on the close button of the application window. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Message box') self.show() def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
在關閉QWidget
時會生成QCloseEvent
。咱們須要從新實現closeEvent()
這個事件處理器來改變控件的行爲。
reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
咱們要顯示帶有兩個按鈕(Yes和No)的消息對話框。第一個字符串會顯示在標題欄,第二個字符串是對話框的消息文本。第三個參數設置了顯示在對話框中的按鈕。最後那個參數指定了默認的按鈕,也就是默認取得鍵盤焦點的按鈕。返回結果保存在reply
變量中。
if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore()
咱們在這裏對返回值進行匹配。當點擊了Yes按鈕時,咱們會接受該事件,從而關閉該控件並退出程序;不然就忽略這個關閉事件。
下面的腳本會將窗體置於桌面中心。
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This program centers a window on the screen. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.resize(250, 150) self.center() self.setWindowTitle('Center') self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
QtGui.QDesktopWidget
提供了關於用戶桌面的信息,包括屏幕尺寸。
self.center()
center()方法中包含了窗體居中的代碼。
qr = self.frameGeometry()
獲得一個指定了主窗體形狀的矩形。
cp = QDesktopWidget().availableGeometry().center()
指出顯示器的屏幕分辨率並根據分辨率找出屏幕的中心點。
qr.moveCenter(cp)
將矩形移動到屏幕中心,尺寸不變。
self.move(qr.toLeft())
將窗體的左上角移動到矩形qr的左上角,窗體與矩形重合,從而將窗體置於屏幕中心。
在這部分教程中咱們學到了一些PyQt5基礎