由于最近在学习pyqt5的相关知识,在网上找了几篇教程看,于是就写了这篇学习笔记。本文只是一些案例的代码以及演示,详细的讲解请看原文。
原文链接:https://zetcode.com/gui/pyqt5/
中文翻译:http://www.360doc.com/content/19/1022/14/12906439_868371487.shtml
2、带窗口的图标
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('FirstGUI')
w.show()
sys.exit(app.exec_())
3、提示框
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton
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')
btu = QPushButton('Button', self)
btu.setToolTip('This is a <b>QWidget<b> widget')
btu.resize(btu.sizeHint())
btu.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_())
4、关闭窗口
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
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_())
点击Quit按钮就会关闭窗口
5、消息盒子
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
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_())
6、窗口居中
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(400, 250)
self.center()
self.setWindowTitle('Center')
self.show()
def center(self):
qr = self.frameGeometry() # 获得主窗口所在的框架
cp = QDesktopWidget().availableGeometry().center() #获取显示器的分辨率,得到屏幕中间点的位置
qr.moveCenter(cp) #把主窗口框架的中心点放置到屏幕的中心位置
self.move(qr.topLeft()) #通过move把主窗口的左上角移动到其框架的左上角,实现窗口居中
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())