【问题标题】:Problem with SIGNAL - SLOT, aboutToQuit()SIGNAL 问题 - SLOT,aboutToQuit()
【发布时间】:2011-09-24 19:30:52
【问题描述】:

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

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)
  • 我们不需要类来定义插槽。通过使用 @pyqtSlot() 装饰器,任何方法都可以是 Slot。
  • 我在代码中添加了 noClassMethod()。
  • @Mat ,您的建议帮助我走得更远。现在我发现了其他 3 种方法。我猜它是关于旧式与新式
  • 我不会删除错误消息,以供将来可能的读者阅读。

谢谢大家:-)

【问题讨论】:

    标签: python qt python-3.x pyqt


    【解决方案1】:

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

    尝试:

    class Klose:
      def closingStuff(self):
        print("bye")
    
    ...
    app.connect(app, SIGNAL("aboutToQuit()"), k.closingStuff)
    

    不确定在 PyQt 中是否有必要,但信号和槽通常预计来自/去往 QObjects。如果您的 PyQt 版本足够新,New-style signals and slots 可能会很有趣。

    【讨论】:

    【解决方案2】:

    在 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)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多