QMainWindow主窗口为用户提供了一个应用程序框架,它有自己的布局,可以在布局中添加控件。
QMainWIndow、QWidget、QDialg
三个类都是用来创建窗口的,可以直接使用,也可以继承后使用。
QMainWindow
窗口可以包含菜单栏、工具栏、状态栏、标题栏等。最常见的窗口形式,也是GUI程序的主窗口。
Dialog
是对话框窗口的基类。对话框主要用来执行短期任务,或者与用户进行互动,它可以是模态的,也可以是非模态的。
如果不确定,或者可能作为顶层窗口,也有可能嵌入其他窗口中,那么就使用QWidget
类
如果一个窗口包含一个或多个窗口,那么这个窗口就是父窗口,被包含的窗口就是子窗口。没有父窗口的窗口就是顶层窗口。
在PyQt中,主窗口中会有一个控件(QWidget)占位符来占着中心窗口,可以使用setCentralWidet()
来设置中心窗口。
重要的方法列表
方法 | 描述 |
---|---|
addToolBar() | 添加工具栏 |
centralWidget() | 返回窗口中心的一个控件,未设置的时候返回NULL |
menuBar() | 返回主窗口的菜单栏 |
setCentralWidget() | 设置窗口中心的控件 |
setStatusBar() | 设置状态栏 |
statusBar() | 获得状态栏对象后,调用状态栏对象的showMessage(message,int timeout=0)方法,显示状态栏信息,其中第一个参数是要显示的状态栏的信息,第二个参数是信息停留的时间,单位是毫秒,默认是0,表示一直显示状态栏信息。 |
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QIcon
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super(MainWindow,self).__init__(parent)
self.resize(400,200)
self.status = self.statusBar()
self.status.showMessage("这是状态栏提示",5000)
self.setWindowTitle("PyQt MainWindow 例子")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("./images/cartoon1.ico"))
form = MainWindow()
form.show()
sys.exit(app.exec_())
使用QMainWindow类的statusBar()方法创建状态栏,然后使用showMessage()方法将提示信息显示在状态栏中。
QMainWindow
利用QDesktopWidget类来实现主窗口居中显示
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QDesktopWidget, QApplication, QMainWindow
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()
size = self.geometry()
self.move((screen.width()-size.width())/2,(screen.height()-size.height())/2)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
QDesktopWidget
是描述显示屏幕的类,通过QDesktopWidget().screenGeometry()
来获得屏幕的大小
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow, QHBoxLayout, QPushButton, QApplication, QWidget
class WinForm(QMainWindow):
def __init__(self, parent = None):
super(WinForm, self).__init__(parent)
self.setWindowTitle("关闭窗口")
self.button1 = QPushButton("关闭主窗口")
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 = 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_())
当点击关闭主窗口
后,将关闭显示的窗口
self.button1.clicked.connect(self.onButtonClick)
通过按钮的clicked信号与onBottonClick槽函数关联起来。