PythonTip >> 博文 >> PyQt

Eli Bendersky: New-style signal-slot connection mechanism in PyQt

zihua 2014-01-20 23:01:51 点击: 1022 | 收藏

In most of the PyQt code samples you find online and in books (including, I confess, my examples and blog posts) the "old-style" signal-slot connection mechanism is used. For example, here’s a basic push-button window:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QMainWindow):
    def __init__(self, parent=None):
        super(MyForm, self).__init__(parent)
        the_button = QPushButton('Hello')
        self.connect(the_button, SIGNAL('clicked()'), self.on_hello)

    def on_hello(self):

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = MyForm()

The relevant code is:

self.connect(the_button, SIGNAL('clicked()'), self.on_hello)

Apart from being verbose and un-Pythonic, this syntax has a serious problem. You must type in the C++ signature of the signal exactly. Otherwise, the signal just won’t fire, without an exception or any warning. This is a very common mistake. If you think that clicked() is a simple enough signature to write, how about these ones (taken from real code):

SIGNAL('marginClicked(int, int, Qt::KeyboardModifiers)')

The "new-style" signal-slot connection mechanism is much better. Here’s how the button click connection is done:


作者:zihua | 分类: PyQt | 标签: pyqt | 阅读: 1022 | 发布于: 2014-01-20 23时 |