PyQt5信号和插槽简单代码说明

时间:2016-03-21 15:09:50

标签: qt pyqt pyqt5 qt-signals

我对使用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 个答案:

答案 0 :(得分: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_())
相关问题