【问题标题】:PyQt5 signal and slot simple code explanationPyQt5信号槽简单代码解释
【发布时间】:2016-03-21 15:09:50
【问题描述】:

我对使用 PyQt 非常陌生,并且正在尝试了解信号槽机制。不幸的是,PyQt 的文档通常会导致语法和参数几乎不一样的 Qt 页面。我试图在下面的简单示例中找出两件事。

1) QAction::triggered() 是一个 void 函数,那么我们如何在理论上由 trigger() 方法返回的某种对象上调用 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_())

【问题讨论】:

    标签: qt pyqt pyqt5 qt-signals


    【解决方案1】:

    1/ : 连接信号的语法自动携带参数到专用回调 在你的情况下,没有论据。 我简化了您的代码以向您展示回调机制

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

    QApplication documentation 中提取:

    可以通过 instance() 函数访问 QApplication 对象,该函数返回与全局 qApp 指针等效的指针。

    全局 qApp 指针指向此应用程序对象。只应创建一个应用程序对象。

    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_())
    

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2013-10-08
      • 2019-04-20
      • 2016-07-27
      • 1970-01-01
      相关资源
      最近更新 更多