PyQt5信号与槽简单代码解释

PyQt5 signal and slot simple code explanation

我刚开始使用 PyQt,正在尝试了解信号槽机制。不幸的是,PyQt 的文档通常会导致语法和参数几乎不相同的 Qt 页面。我试图在下面的简单示例中找出两件事。

1) QAction::triggered() 是一个 void 函数,那么我们如何在理论上由 triggered() 方法返回的某种对象上调用 QAction::triggered.connect()。

2) "qApp" 是什么。我不知道 qApp 是什么类型,也不知道它是由 PyQt 在何处创建的,但它对我来说似乎无处不在,只是在方便的时候使用。

我的部分误解可能来自于 Qt/PyQt 中的 C++ 和 python 函数实现并不相同,但我们应该无需任何形式的理解就可以理解发生了什么python 文档。

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('exit24.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_())

1/ : 连接信号的语法自动携带参数到专用回调 在你的情况下,没有争论。 我简化你的代码,给你看回调机制

2/ : qApp 是您的 Qapplication 实例的一种快捷方式。您可以将其替换为您的 QApplication 实例,如下例所示。

摘自 QApplication documentation :

The QApplication object is accessible through the instance() function that returns a pointer equivalent to the global qApp pointer.

The global qApp pointer refers to this application object. Only one application object should be created.

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

class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        exitAction = QAction('Exit', self)
        exitAction.triggered.connect(self.this_call)
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)
        self.show()

    def this_call(self):
        print('bye bye')
        app.quit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())