PyQt5学习笔记(2)菜单,工具栏,事件和信号

s
参考:PyQt5 教程, 该文档翻译自PyQt5 tutorial

PyQt5菜单和工具栏

在这部分PyQt5教程中,我们将创建菜单和工具栏。

1.主窗口

QMainWindow 类提供了一个主要的应用程序窗口。应用程序可以在QMainWindow 上添加状态栏,工具栏和菜单栏。

2.状态栏:用于显示状态信息

QMainWindow类第一次调用statusBar()方法创建一个状态栏。后续调用返回的状态栏对象。showMessage()状态栏上显示一条消息。

示例11:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        # 用 QMainWindow创建状态栏的小窗口。
        self.statusBar().showMessage('Ready')

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Statusbar')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

3.菜单栏

菜单栏是常见的窗口应用程序的一部分。

示例12:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        # 创建一个菜单。这个菜单将终止应用程序。

        exitAction = QAction(QIcon('exit.png'), '&Exit', self)    
        # 定义该操作的快捷键
        exitAction.setShortcut('Ctrl+Q')
        # 创建一个鼠标指针悬停在该菜单项上时的提示。
        exitAction.setStatusTip('Exit application')
        # 当我们点击菜单的时候,调用qApp.quit,终止应用程序。
        exitAction.triggered.connect(qApp.quit)

        self.statusBar()

        #创建一个菜单栏
        menubar = self.menuBar()
        #添加菜单
        fileMenu = menubar.addMenu('&File')
        #添加事件
        # QAction可以操作菜单栏,工具栏,或自定义键盘快捷键。
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Menubar')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  

4.工具栏

工具栏提供了一个快速访问的入口。

示例13:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        # 创建一个QAction事件。该事件有一个标签、图标和快捷键。退出窗口的方法
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        # 创建一个简单的工具栏。工具栏有有一个按钮,点击关闭窗口。
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Toolbar')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

5.综合界面

示例14:创建一个菜单条,工具栏和状态栏的小窗口

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication
from PyQt5.QtGui import QIcon


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               
        # 创建了一个QTextEdit,并把他设置为窗口的布局
        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)

        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        toolbar = self.addToolBar('Exit')
        toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Main window')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

关于 setCentralWidget(textEdit) , 参考 这里:

PySide2.QtWidgets.QMainWindow.setCentralWidget(widget)¶
Parameters
    widget – PySide2.QtWidgets.QWidget

Sets the given widget to be the main window’s central widget.

Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.

PyQt5事件和信号:探讨PyQt5中的事件Event

1.事件 Event

所有的GUI程序都是事件驱动的。事件的触发:

  • 事件主要由用户触发
  • 也可能有其他触发方式:例如网络连接、window manager或定时器。

当我们调用QApplication的exec_()方法时会使程序进入主循环。主循环会获取并分发事件。

在事件模型中,有三个参与者:

  • 事件源: 事件源是状态发生变化的对象。它会生成事件。
  • 事件对象: 事件(对象)封装了事件源中状态的变动,用来描述事件
  • 事件接收者:事件接收者是要通知的对象。

事件源对象:生成事件 ===>【事件】 <=== 事件接收者:处理事件

PyQt5有一个独特的 signal&slot(信号槽)机制来处理事件。信号槽用于对象间的通信。signal在某一特定事件发生时被触发,slot可以是任何callable对象。当signal触发时会调用与之相连的slot。

2.信号槽 Signals & slots:信号和槽

示例15:一个使用信号槽的PyQt5例子

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider, 
    QVBoxLayout, QApplication)


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        lcd = QLCDNumber(self)
        sld = QSlider(Qt.Horizontal, self)

        vbox = QVBoxLayout()
        vbox.addWidget(lcd)
        vbox.addWidget(sld)

        self.setLayout(vbox)
        # lcd的值会随着滑块的拖动而改变。
        # 在这里我们将滚动条的valueChanged信号连接到lcd的display插槽
        # sender是发出信号的对象。receiver是接收信号的对象。
        # slot(插槽)是对信号做出反应的方法
        sld.valueChanged.connect(lcd.display)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Signal & slot')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

3.重新实现事件处理器

在PyQt5中常通过重新实现事件处理器来处理事件。

示例16:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Event handler')
        self.show()


    def keyPressEvent(self, e):
        # 重新实现了keyPressEvent()事件处理器。
        # 我们按下Escape键会使程序退出。
        if e.key() == Qt.Key_Escape:
            self.close()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

4.事件发送者:有时需要知道信号是由哪个控件发出的,对此PyQt5提供了sender()方法

示例17:

# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      

        btn1 = QPushButton("Button 1", self)
        btn1.move(30, 50)

        btn2 = QPushButton("Button 2", self)
        btn2.move(150, 50)

        # 两个按钮连接到了同一个插槽
        btn1.clicked.connect(self.buttonClicked)            
        btn2.clicked.connect(self.buttonClicked)

        self.statusBar()

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Event sender')
        self.show()


    def buttonClicked(self):
        # 在buttonClicked()方法中
        # 通过调用sender()方法来判断当前按下的是哪个按钮
        # 通过调用sender()方法来判断信号源, 并将其名称显示在窗体的状态栏中。
        sender = self.sender()
        self.statusBar().showMessage(sender.text() + ' was pressed')


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

5.发出信号

通过QObject创建的对象可以发出信号。

示例18:

下面的示例演示了如何发出自定义信号

# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication


class Communicate(QObject):
    # 信号closeApp是Communicate的类属性,它由pyqtSignal()创建
    closeApp = pyqtSignal() 


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):      
        # 我们用 Communicate(QObject) 创建了一个名为closeApp的信号。
        # 这个信号会在按下鼠标时触发: mousePressEvent(self, event)
        # 它连接着QMainWindow的close()插槽
        self.c = Communicate()
        # 自定义closeApp信号连接到QMainWindow的close槽
        self.c.closeApp.connect(self.close)       

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Emit signal')
        self.show()


    def mousePressEvent(self, event):
        # 当在窗体上点击鼠标时会触发closeApp信号,使程序退出。
        self.c.closeApp.emit()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

正文完
 
评论(没有评论)