关于SIGNAL - SLOT的aboutToQuit()问题

3 投票
2 回答
2888 浏览
提问于 2025-04-16 20:30

我的应用程序只能通过右键点击托盘图标,然后选择“退出”来关闭。

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() 装饰器。
  • 我在代码中添加了noClassMethod()。
  • @Mat,你的建议让我更进一步。现在我找到了三种其他的方法。我想这和 旧风格与新风格 有关。
  • 我不会删除错误信息,以便将来可能的读者参考。

感谢大家 :-)

2 个回答

1

在PyQt5中,有一种新的信号叫做:app.aboutToQuit.connect(...)。

def app_aboutToQuit():
    print('app_aboutToQuit()')

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

PyQt中的信号和槽的写法和C++的有点不一样。

可以试试这个:

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

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

我不太确定在PyQt中这是否必要,但一般来说,信号和槽通常是从QObjects发出或接收的。如果你的PyQt版本比较新,可以看看新式信号和槽,可能会对你有帮助。

撰写回答