PyQt5(1) 簡單得不能再簡單的應用程式
阿新 • • 發佈:2019-02-02
# 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_()) #安全退出