如何使用QStateMachine addtransition自定义信号

时间:2014-01-08 01:08:20

标签: python qt4 pyqt4 qstatemachine

试图弄清楚如何结合QStateMachine使用我自己的自定义信号。我从here的一个简单示例开始。现在我正在尝试创建一个新信号mysignal并触发它的转换。但我无法弄清楚如何构建对addtransition的调用,或者如何使用SIGNAL("clicked()")语法来引用mysignal

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

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    button = QPushButton()
    machine = QStateMachine()

    off = QState()
    off.assignProperty(button, 'text', 'Off')
    off.setObjectName('off')

    on = QState()
    on.setObjectName('on')
    on.assignProperty(button, 'text', 'On')

    mysignal = pyqtSignal()

    off.addTransition(mysignal, on)
    # Let's use the new style signals just for the kicks.
    on.addTransition(button.clicked, off)

    machine.addState(off)
    machine.addState(on)
    machine.setInitialState(off)
    machine.start()
    mysignal.emit()
    button.resize(100, 50)
    button.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:3)

必须将自定义信号定义为类属性(请参阅PyQt文档中的New-style Signal and Slot Support)。因此,您的示例中的代码需要重构,以便所有设置都发生在窗口小部件子类的__init__中。

下面是一个演示(为了触发自定义信号及其状态转换,只要按钮文本显示“Foo”,就必须在行编辑中键入“foo”):

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    customSignal = QtCore.pyqtSignal()

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.textChanged.connect(self.handleTextChanged)
        self.button = QtGui.QPushButton(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.machine = QtCore.QStateMachine()
        self.off = QtCore.QState()
        self.off.assignProperty(self.button, 'text', 'Off')
        self.on = QtCore.QState()
        self.on.assignProperty(self.button, 'text', 'On')
        self.foo = QtCore.QState()
        self.foo.assignProperty(self.button, 'text', 'Foo')
        self.off.addTransition(self.button.clicked, self.on)
        self.on.addTransition(self.button.clicked, self.foo)
        self.foo.addTransition(self.customSignal, self.off)
        self.machine.addState(self.off)
        self.machine.addState(self.on)
        self.machine.addState(self.foo)
        self.machine.setInitialState(self.off)
        self.machine.start()

    def handleTextChanged(self, text):
        if text == 'foo':
            self.edit.clear()
            self.customSignal.emit()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.setGeometry(500, 300, 100, 100)
    sys.exit(app.exec_())