在PyQt 4中处理事件的正确方法是什么?

时间:2009-12-15 00:45:45

标签: python pyqt4

我见过这样的例子:

self.connect(self.ui.add_button, QtCore.SIGNAL('clicked()'),self.printer)

这样的例子:

self.ui.add_button.clicked.connect(self.printer)

我刚开始学习Qt;我应该关注哪一个?

3 个答案:

答案 0 :(得分:3)

我认为第二个例子只有一些Qt版本(较新的版本)支持,而第一个版本则由旧版本支持。 但是,两者都是正确的。

答案 1 :(得分:0)

AFAIK,如果信号过载,较新的风格不起作用,所以

self.ui.add_button.clicked.connect(self.printer)
如果还有一个

,则不能使用

clicked(float, float)

所以你必须回归旧款式。了解两者总是好的。

答案 2 :(得分:0)

我知道这篇文章很老了,但我偶然发现了它, 也许你也会这样,现在这可以节省你的一天;)好吧...... 顺便说一句,这是我在SO的第一篇文章,是的!是的!

警告,我没有测试这段代码,我刚刚复制了一段时间前我写过的一些代码片段,所以,可能会有一些错误,但我希望无论如何都有帮助

PyQt的新风格简要说明:

# notice that the signal declarations are at class level (not inside some method)

class MyClass(QObject):    # must subclass QObject (or subclass)

    # declaring signals
    mySimpleSignal = pyqtSignal()
    mySignalWithArguments = pyqtSignal(int, list)
    myOverloadedSignal = ([int, object],[str,object])

    def __init__(self, parent=None):
        super(MyClass,self).__init__(parent=parent)    # remember to init the super class
        [...]

    # methods
    [...]

    # connecting signals
    def connectSignalsMethod(self):
        # connecting simple signal
        self.mySimpleSignal.connect(self.mySlot)
        # connecting signal with arguments
        self.mySignalWithArguments.connect(self.mySlotWithArguments)
        # connecting overloaded signals
        self.myOverloadedSignal[int, object].connect(self.mySlot1)
        self.myOverloadedSignal[str, object].connect(self.mySLot2)

        # same syntax for disconnect()


    # emitting signals
    def emitSignalsMethod(self):
        # emitting simple signal
        self.mySimpleSignal.emit()
        # emitting signal with arguments
        self.mySignalWithArguments.emit(123,['this','is','a','list'])
        # emitting overloaded signal
        myOverloadedSignal[str,object].emit('this is a string', myObject)


    # my slots
    @pyqtSlot()
    def mySlot(self):
        print('hey!')

    @pyqtSlot(int, list)
    def mySlotWithArguments(self, someNumber, someList):
        print('got a number: %d and a list: %s' % (someNumber, someList))

    @pyqtSlot(int, object)
    def mySlot1(self, intArg, objectArg):
        print('got an int and an object')

    @pyqtSlot(str, object)
    def mySlot2(self, str, object):
        print('got a string and an object')

    # an overloaded slot
    @pyqtSignal(int)
    @pyqtSignal(str)
    def overloadedSlot(someArgument)
        print('got something: %s' % someArgument)

否则,试试这个 http://www.harshj.com/2010/05/06/pyqt-faq-custom-signals-jpeg-mouse-hovers-and-more/#custom

编辑: 事件和信号不一样,你上面看到的是信号