connect function in pyqt5 does not work

2020-05-09 12:19发布

问题:

I recently moved from pyside to pyqt5 and there is a problem. I looked it up online and apparently, it already happened to people who used pyqt4 and moved to pyqt5. However, it didn't really help... I tried to add pyqtSignal after Qobject but it is still not working. Please help. these are my code lines:

QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"),Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)

and this is what appears when I run it:

AttributeError: type object 'QObject' has no attribute 'connect'

回答1:

from the docs:

connect(slot[, type=PyQt5.QtCore.Qt.AutoConnection[, no_receiver_check=False]])

Connect a signal to a slot. An exception will be raised if the connection failed. Parameters:

  • slot – the slot to connect to, either a Python callable or another bound signal.
  • type – the type of the connection to make.
  • no_receiver_check – suppress the check that the underlying C++ receiver instance still exists and deliver the signal anyway.

for your example:

self.buttonBox.accepted.connect(Dialog.accept) # pyqt5

QtCore.QObject.connect(self.buttonBox.rejected, Dialog.reject) # pyqt4

As a sidenote, "Dialog" sounds like a class, you probably want to connect to an instance, else think about naming your instances with lowercase front-letters ...