创建一个pyqt5应用程序
使用了PyQt5中的QtWidgets模块
基本控件位于pyqt5.qtwidgets模块中。
from PyQt5. QtWidgets import QApplication, QWidget
每一个pyqt5应用程序必须创建一个应用程序对象。sys.argv参数是一个列表,sys.argv就是运行程序时候获取命令行参数。
app = QApplication( sys. argv)
QWidget部件是pyqt5所有用户界面对象的基类,它为QWidget提供默认构造函数,默认构造函数没有父类。
w = QWidget( )
w. resize( 300 , 300 )
w. move( 300 , 300 )
setWindowTitle(“Simple”)设置窗口的标题为Simple
w. setWindowTitle( "Simple" )
w. show( )
app.exet_()是指程序一直循环运行直到主窗口被关闭终止进程(如果没有这句话,程序运行时会一闪而过) 其实我感觉这个sys.exit()其实没什么作用,他其实就是用来反映程序终止的状态的,在它有父进程的情况下最好有这个sys.exit()通过她的返回值可以判断子进程的状态。而在没有子进程的程序中,其实sys.exit(app.exec_())和app.exec_()效果是一样的。
设置应用程序的图标
使用的是PyQt5.QtGui模块
首先建立一个类,继承所有用户界面的基类QWidget:
class Example ( QWidget) :
def __init__ ( self) :
super ( ) . __init__( )
self. initUI( )
def initUI ( self) :
self. setGeometry( 300 , 300 , 300 , 300 )
self. setWindowIcon( QIcon( "web.png" ) )
self. show( )
setGeometry(a,b,c,d)方法设置窗口的位置和大小 setWindowIcon()方法用来设置程序图标,它需要一个QIcon类型的对象作为参数。调用QIcon构造函数时,我们需要提供要显示的图标的路径(相对或绝对路径)。同时注意:使用QIcon类型必须导入此模块from PyQt5.QtGui import QIcon
显示提示语
QToolTip. setFont( QFont( "SansSerif" , 10 ) )
创建一个按钮PushButton并为他设置一个tooltip 创建一个提示,我们称之为setToolTip()方法,在此我们使用的是富文本格式
from PyQt5. QtWidgets import QPushButton
btn = QPushButton( 'Button' , self)
btn. setToolTip( 'This is a <b>QPushButton</b> widget' )
btn. resize( btn. sizeHint( ) )
关闭窗口
使用的PyQt5的QtCore模块
通过编程来关闭窗口 先创建一个按钮QPushButton 单击按钮关闭窗口
from PyQt5. QtCore import QCoreApplication
qbtn = QPushButton( "Quit" , self)
qbtn. cliked. connect( QCoreApplication. instance( ) . quit)
PyQt5使用的是OPP编程
面向对象的编程有三个重要的方面:类、变量和方法。上面我们创建一个新的类Example,Example继承自QWidget类。
消息框
当我们关闭窗口的时候会弹出一个提示信息让你确认是否关闭 使用了QtWidgets中的QMessageBox方法 在写的Example类中重写父类的closeEvent方法:
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( )
窗口显示在屏幕的中间
"""
Py40 PyQt5 tutorial
This program centers a window
on the screen.
author: Jan Bodnar
website: py40.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类提供了用户的桌面信息,包括屏幕大小。