SIGNAL - SLOT存在问题,关于aboutToQuit()

3

我的应用程序只能通过右键单击托盘图标并按下“退出”来退出:

class DialogUIAg(QDialog):
    ...
    self.quitAction = QAction("&Quit", self, triggered=qApp.quit)

下面的模块是应用程序的起点:
#!/usr/bin/env python

import imgAg_rc
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import appLogger

from runUIAg import *

class Klose:
    """ Not sure if i need a Class for it to work"""
    def closingStuff(self):
        print("bye")

@pyqtSlot()
def noClassMethod():
    print("bye-bye")

app = QApplication(sys.argv)
QApplication.setQuitOnLastWindowClosed(False)

k = Klose()
app.connect(app, SIGNAL("aboutToQuit()"), k,SLOT("closingStuff()")) #ERROR

app.connect(app, SIGNAL("aboutToQuit()"), k.closingStuff)   # Old-Style
app.connect(app, SIGNAL("aboutToQuit()"), noClassMethod)    # Old-Style

app.aboutToQuit.connect(k.closingStuff)   # New-Style
app.aboutToQuit.connect(noClassMethod)    # New-Style

winUIAg = DialogUIAg()
winUIAg.show()
app.exec_()

我的意图是在应用程序即将退出时执行一段代码。
这是我收到的错误信息:

$ ./rsAg.py
Traceback (most recent call last):
  File "./rsAgent.py", line 20, in <module>
    app.connect(app, SIGNAL("aboutToQuit()"), k,SLOT("closingStuff()"))
TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'Klose'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'Klose'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'Klose'

我刚开始学习Python和Qt,希望你能帮助我。


编辑:

  • 我忘记提到版本(Python:3.2,pyQt:4.8.4)。
  • 我们不需要使用类来定义Slot。通过使用@pyqtSlot()装饰器,任何方法都可以成为Slot。
  • 我在代码中添加了noClassMethod()。
  • @Mat,你的建议帮助我进一步了解。现在我发现还有其他三种方法可以实现它。我猜这可能是关于“旧式”与“新式”的区别。
  • 出于可能会有未来读者的考虑,我不会删除错误消息。

谢谢大家 :-)

2个回答

5

PyQt的信号/槽语法与C++并不完全相同。

可以尝试使用以下方法:

class Klose:
  def closingStuff(self):
    print("bye")

...
app.connect(app, SIGNAL("aboutToQuit()"), k.closingStuff)

在PyQt中不确定是否必要,但通常预期信号和槽来自/去往QObjects。如果您的PyQt版本足够新,则新式信号和槽可能会引起兴趣。


2
在PyQt中,槽可以是Python函数(类不是必需的)。文档:http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/old_style_signals_slots.html#connecting-signals-and-slots - pedrotech

1
在PyQt5中,新式信号:app.aboutToQuit.connect(...)。
def app_aboutToQuit():
    print('app_aboutToQuit()')

app = QtWidgets.QApplication(sys.argv)
app.aboutToQuit.connect(app_aboutToQuit) 

这在PyQt4中也适用,例如 app = QtGui.QApplication.instance(); app.aboutToQuit.connect(app_aboutToQuit) - dbr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接