窗口类型
QMainWindow 主窗口(菜单栏,标题栏,工具栏,状态栏)
QWidget 任意时候都可用
QDialog 对话窗口的基类
创建主窗口
代码示例
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow , QApplication
from PyQt5.QtGui import QIcon
class MainWidget(QMainWindow):
def __init__(self,parent=None):
super(MainWidget,self).__init__(parent)
# 设置主窗体标签
self.setWindowTitle("QMainWindow 例子")
# 设置窗口尺寸
self.resize(400, 200)
# 设置状态栏(,显示毫秒数)
self.status = self.statusBar()
self.status.showMessage("这是状态栏提示",5000)
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("./images/cartoon1.ico"))
main = MainWidget()
main.show()
sys.exit(app.exec_())
cartoon.ico
主窗口居中显示
代码示例
from PyQt5.QtWidgets import QDesktopWidget, QApplication ,QMainWindow
import sys
class Winform( QMainWindow):
def __init__(self, parent=None):
super( Winform, self).__init__(parent)
self.setWindowTitle('主窗口放在屏幕中间例子')
self.resize(370, 250)
self.center()
def center(self):
# 计算屏幕的大小
screen = QDesktopWidget().screenGeometry()
# 获取QWidget窗口的大小
size = self.geometry()
# 注意换为int以防出现浮点
self.move(int((screen.width() - size.width()) / 2), int((screen.height() - size.height()) / 2))
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
关闭主窗口
代码示例
from PyQt5.QtWidgets import QMainWindow, QHBoxLayout, QPushButton, QApplication, QWidget
import sys
class WinForm(QMainWindow):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.resize(330, 100)
self.setWindowTitle('关闭主窗口例子')
# 设置按钮
self.button1 = QPushButton('关闭主窗口')
# 按钮绑定的clicked信号与槽onButtonClick关联
self.button1.clicked.connect(self.onButtonClick)
layout = QHBoxLayout()
layout.addWidget(self.button1)
main_frame = QWidget()
main_frame.setLayout(layout)
self.setCentralWidget(main_frame)
def onButtonClick(self):
#sender 是发送信号的对象,此处发送信号的对象是button1按钮
sender = self.sender()
print(sender.text() + ' 被按下了')
qApp = QApplication.instance()
qApp.quit()
if __name__ == "__main__":
app = QApplication(sys.argv)
form = WinForm()
form.show()
sys.exit(app.exec_())
单击关闭窗口运行栏获得信息