标签:
自定义一个属于自己的窗口,初始化时自动设置好在屏幕中央显示,重写退出事件的触发器 closeEvent(),并增加了设置图标,简化设置标题的函数名,其它类可以继承它:
1 # -*- coding: utf-8 -*- 2 3 import time 4 import sys 5 from PyQt4 import QtGui, QtCore 6 7 8 class MyQwidget(QtGui.QWidget): 9 10 def __init__(self, title=None, icon=None): 11 QtGui.QWidget.__init__(self) 12 self.setGeometry(300, 200, 600, 500) 13 self.center() 14 self.setTitle(title) 15 self.setIcon(icon) 16 17 def setTitle(self, title=None): 18 if title != None: 19 self.setWindowTitle(title) 20 21 def setIcon(self, icon=None): 22 if icon != None: 23 self.setWindowIcon(QtGui.QIcon(icon)) 24 25 def resize(self, width, height): 26 QtGui.QWidget.resize(self, width, height) 27 self.center() 28 29 def center(self): 30 screen = QtGui.QDesktopWidget().screenGeometry() 31 size = self.geometry() 32 self.move((screen.width() - size.width()) / 2, 33 (screen.height() - size.height()) / 2) 34 35 def closeEvent(self, event): 36 reply = QtGui.QMessageBox.question( 37 self, ‘Message‘, ‘Are you sure to close?‘, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) 38 if reply == QtGui.QMessageBox.Yes: 39 event.accept() 40 else: 41 event.ignore() 42 43 44 class Widget2(MyQwidget): 45 pass 46 47 48 class MainWindow(QtGui.QMainWindow, MyQwidget): 49 50 def __init__(self, parent=None): 51 QtGui.QMainWindow.__init__(self) 52 self.resize(300, 200) 53 self.setTitle(‘statusbar‘) 54 self.statusBar().showMessage(‘Ready‘) 55 56 57 app = QtGui.QApplication(sys.argv) 58 59 w1 = Widget2(icon=‘image\\RK.gif‘, title=‘MyQwidget‘) 60 w1.show() 61 62 w2 = Widget2() 63 w2.setTitle(‘hehe‘) 64 w2.setIcon(‘image\\fire.gif‘) 65 w2.resize(400, 300) 66 w2.show() 67 68 w3 = MainWindow() 69 w3.show() 70 71 sys.exit(app.exec_())
运行后截图如下:(均处于整个屏幕的中央)
标签:
原文地址:http://www.cnblogs.com/Newdawn/p/4637786.html