First programs in PyQt5

原文:http://zetcode.com/gui/pyqt5/


Simple example

本节第一个例子用于展示一个小的窗口,但是这个窗口可以做到,调整尺寸,最大化,最小化。

代码

#!/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(800, 500)
    w.move(100, 100)
    w.setWindowTitle('Simple Example')
    w.show()
    sys.exit(app.exec_())


上述代码的分析:

app = QApplication(sys.argv)
每一个PyQt5的应用都创建一个application对象,sys.argv不用多说,shell中调用该py脚本的参数。

w = QWidget()
QWidget组件在PyQt5中是所有用户接口对象的基类。我们创建QWidget是采用默认的构造方法(没有父类),没有父类的Widget组件称为window。

w.resize(800, 500)
resize()方法,调整Widget组件窗口的大小,800px宽,500px高。

w.move(100, 100)
move()方法移动widget组件到屏幕上x=300,y=300的位置。

w.setWindowTitle('Simple Example')

设置窗口名为'Simple Example'

 show() 方法将该Widget组件在屏幕上显示. 一个Widget组件先被在内存中创建,然后在屏幕上显示。

sys.exit(app.exec_())

最后进入,该应用的主循环中。事件处理从该处开始,主循环从window system接收到事件,然后将这些事件发送给该application widgets。当我们调用exec()函数,或者main Widget被销毁时,主循环结束。sys.exit()方法确保clean的退出。系统环境将会被通知应用是怎样结束的。

exec是Python关键字,用exec_()来代替。


代码运行,如图。



An application icon

application icon通常是在应用程序标题栏左上角的小图像。下面展示PyQt5的实现。

#!/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 Example')
        self.setWindowIcon(QIcon('icon.png'))        
    
        self.show()
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  

代码分析:

前一个例子使用面向过程的编码style。Python支持面向过程和面向对象的style。PyQt5编程是面向对象的编程。

所以该例子中创建了一个类Example。

class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        ...

该Example类继承自QWidget类,这意味着我们调用两个构造方法:第一个是Example类的构造方法,第二个是被继承类的构造方法。

super()方法返回了Example类的父类对象,并且我们调用了它的的构造方法。__init__()方法是Python中的构造方法。


GUI的创建被交给了initUI()方法:

self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon Example')
self.setWindowIcon(QIcon('icon.png'))
上述三个方法都继承自QWidget类,setGeometry()函数做了两件事:设定窗口位置和它的大小。

前两个参数为窗口window的坐标x和y,第三个和第四个参数分别为窗口Window的宽和高。

事实上,他将resize()和move()两个方法结合为一个方法。

最后一个方法setWindowIcon设置了该应用的Icon,为了调用该方法,我们创建了一个QIcon对象,QIcon创建时接收图片的路径作为参数。

if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  
最后Application和Example对象被创建,主循环开始。


Showing a tooltip

我们可以为我们所有的widgets组件,提供一个气球状的帮助。

#!/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_())

代码分析:

QToolTip.setFont(QFont('SansSerif', 10))
该静态方法设置了ToolTip的字体。

self.setToolTip('This is a <b>QWidget</b> widget')
调用setTollTip方法,创建tooltip,可以使用富文本格式。


         


Closing a window

关闭窗口可以点击标题栏的X。下面我们通过编写一个Button,点击它关闭窗口,来简单接触信号和槽机制(signals and slots)。

#!/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)
创建一个按钮,为QPushButton的一个实例,第一个参数是该按钮的label,第二个参数为该按钮的父组件。在本例中应为继承QWidget的Example组件。

qbtn.clicked.connect(QCoreApplication.instance().quit)
在PyQt5中,事件处理机制由信号和槽机制建立。

如果我们点击了按钮,信号clicked被发送。槽可以是Qt的槽或任何Python 的一个方法调用。

QCoreApplication类包含了主事件循环;它处理和转发所有事件。

instance()方法给我们返回一个实例化对象。注意QCoreApplication类由QApplication创建。点击信号与结束应用的quit()方法连接。

事件通信在两个对象之间进行:发送者和接受者。发送者是按钮,接受者是应用程序对象。


Message Box

默认情况下,点击标题栏X按钮,QWidget将被关闭。有时我们想更改这种默认行为。

例如,如果我们有个文件在编辑器内打开,做了修改。 我们利用message box来确认这个动作。

#!/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)

我们实现一个message box:有YES和No按钮。

第一个字符串出现在Message Box的标题栏上。第二个字符串显示在对话框上。第三个参数指定了显示在对话框上的按钮集合。最后一个参数是默认选中的按钮,该按钮一开始就获得焦点。

返回值被储存在reply变量中。

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

在这里我们对返回值进行判断。如果点击Yes按钮,我们接受导致组件的关闭和应用的结束事件。否则忽略该关闭事件。


Centering window on the screen

下面的代码展示如何将窗口居中显示到桌面窗口。

#!/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()
我们算出相对于显示器的resolution。并且从该resolution,获得了屏幕中心点。

 qr.moveCenter(cp)
我们的矩形已经设置好了它的宽和高。现在我们把矩形的中心放到屏幕的中间去。矩形的大小并不会改变。

self.move(qr.topLeft())
移动应用窗口的左上方的点到qr矩形的左上方的点,所以窗口居中显示在屏幕上。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值