PyQt5中connect函数无法使用,请求技术协助
Hey there! I totally get the frustration when switching between Qt bindings and hitting unexpected errors like this. Let's break down what's going wrong and how to fix it quickly.
Why You're Seeing This Error
PyQt5 has completely removed the old Qt4-style static QtCore.QObject.connect() method along with the string-based SIGNAL() syntax. That's exactly why you're getting the AttributeError: type object 'QObject' has no attribute 'connect' message—this method no longer exists in PyQt5. Adding pyqtSignal wouldn't help here because that's for defining custom signals, not fixing how you connect built-in ones.
The Correct PyQt5 Way to Connect Signals
PyQt5 uses a much cleaner, type-safe signal-slot syntax where you call the connect() method directly on the signal itself. Here's how to rewrite your code:
# Replace your old connect calls with these self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject)
This works because:
self.buttonBox.acceptedis the built-in signal emitted when the "OK" button is clicked- Calling
.connect()on this signal links it directly to your slot function (Dialog.accept/Dialog.reject) - This syntax is also compatible with PySide2/PySide6, so it's future-proof if you switch back later
If You Need to Maintain Compatibility (Not Recommended)
If for some reason you need to keep a syntax closer to the old style, you can use QtCore.QMetaObject.connectSlotsByName(self), but it requires following strict naming rules:
- Set an
objectNamefor yourbuttonBox(e.g.,self.buttonBox.setObjectName("buttonBox")) - Define slot functions with names like
on_buttonBox_acceptedandon_buttonBox_rejected - Call
QtCore.QMetaObject.connectSlotsByName(self)after setting up your UI
But honestly, the first method is far better—it's more readable, catches errors earlier, and is the standard for modern Qt development.
内容的提问来源于stack exchange,提问作者Alicia Belhassen

