No.2 PyQt学习
新增加了状态栏、菜单栏和工具栏,界面如下:
代码如下:
# -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QMainWindow): def __init__(self): #QtGui.QMainWindow.__init__(self) super(Example, self).__init__() self.initUI() def initUI(self): QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) # 设置一个用来提示消息的字体,10px字体SansSerif #定义主体内容 label = QtGui.QLabel('Are you alone?',self) #label.move(60,60) label.setStatusTip('Yes or No') btn = QtGui.QPushButton('Sure', self) btn.setToolTip('This is a <b>QPushButton</b> widget') #btn.resize(60,25) btn.setGeometry(190, 210, 60, 25) qbtn = QtGui.QPushButton('Quit', self) #qbtn.resize(60, 25) qbtn.setGeometry(270, 210, 60, 25) qbtn.clicked.connect(self.qbtnClick) self.resize( 350, 250) self.statusBar().showMessage('Ready') self.center() self.setWindowTitle('Test') self.setWindowIcon(QtGui.QIcon('flat.png')) exit = QtGui.QAction(QtGui.QIcon('flat.png'), 'Exit', self) exit.setShortcut('Ctrl+Q') exit.setStatusTip('Exit Application') exit.connect(exit, QtCore.SIGNAL('triggered()'), QtGui.qApp, QtCore.SLOT('quit()')) menubar = self.menuBar() #创建一个菜单栏 file = menubar.addMenu('&File') #创建一个菜单 file.addAction(exit) #把动作对象添加到菜单中 toolbar = self.addToolBar('Exit') toolbar.addAction(exit) def qbtnClick(self): reply = QtGui.QMessageBox.question(self, 'Message', 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: quit() def center(self): qr = self.frameGeometry() #得到该主窗口的矩形框架qr cp = QtGui.QDesktopWidget().availableGeometry().center() #屏幕中间点的坐标cp qr.moveCenter(cp) #将矩形框架移至屏幕正中央 self.move(qr.topLeft()) #应用窗口移至矩形框架的左上角点 def closeEvent(self, event): reply = QtGui.QMessageBox.question(self, 'Message', 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() def main(): app = QtGui.QApplication(sys.argv) main = Example() main.show() sys.exit(app.exec_()) if __name__ == '__main__': main()