# encoding = "utf-8"
"""
for test
"""
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QToolTip, QMessageBox, QDesktopWidget
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import QCoreApplication
class MyWindow(QWidget): #從QWighet繼承(主要是爲了它的函數)
def __init__(self):
super().__init__() #不懂
self.initUI() #調用下方的initUI函數
def initUI(self):
self.setGeometry(300, 200, 500, 300) #窗口大小、位置
self.setWindowTitle('MainWindow') #窗口標題
self.setWindowIcon(QIcon('Icon/test1.jpg')) #生成一個QIcon對象,作爲圖標
QToolTip.setFont(QFont('微軟雅黑',15)) #生成一個QFont對象作爲參數,設置提示字的格式
self.setToolTip("這是<b>主窗口</b>") #self的主窗口提示字
button = QPushButton('退出',self) #button按鈕,text爲'退出',屬於'self'
button.setToolTip("點擊<b>退出</b>") #button提示字
button.resize(button.sizeHint()) #button重定義大小爲默認值,.sizeHint前面是該按鈕變量名
button.move(100, 100) #button移動位置
button.clicked.connect(QCoreApplication.instance().quit) #button的點擊與退出聯繫
self.centor()
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message', "確定退出?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
#reply接受消息盒的選擇(Yes/No)
if reply == QMessageBox.Yes: # 經測試,QMessageBox.Yes == 16284, 而QMessageBox.No等於另一個數字
event.accept() #繼續,退出
else:
event.ignore() #忽略,不退出
def centor(self):
cp = QDesktopWidget().availableGeometry().center() #得到中心點的位置
self.move(cp.x()-int(self.width() / 2), cp.y()-int(self.height() / 2)) #計算窗口左上角應處的位置(int/float沒轉化)
if __name__ == "__main__":
app = QApplication(sys.argv) #初始化應用必備
MainWin = MyWindow() #實例化MyWindow類,自動初始化
MainWin.show() #顯示窗口
sys.exit(app.exec_()) #安全退出