在阅读了有限状态机之后,我在 QT 中找到了 QState/QStateMachine API。
但是现在我不知道如何使用它来根据我当前所处的状态运行不同的代码。
让我们看下面的例子:
import sys
from PySide2 import QtCore, QtWidgets
class Form(QtWidgets.QDialog):
def action_a(self):
print("I'm in mode A")
def action_b(self):
print("Mode B is the current mode")
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.button1 = QtWidgets.QPushButton("Run action")
self.button2 = QtWidgets.QPushButton("Change State")
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.button1)
self.layout.addWidget(self.button2)
self.setLayout(self.layout)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
form = Form()
form.show()
state_a = QtCore.QState()
state_b = QtCore.QState()
state_a.assignProperty(form.button2, "text", "To state B")
state_b.assignProperty(form.button2, "text", "To state A")
state_a.addTransition(form.button2, QtCore.SIGNAL("clicked()"), state_b)
state_b.addTransition(form.button2, QtCore.SIGNAL("clicked()"), state_a)
machine = QtCore.QStateMachine()
machine.addState(state_a)
machine.addState(state_b)
machine.setInitialState(state_a)
machine.start()
sys.exit(app.exec_())
我必须在此代码中添加什么才能button1.clicked
连接到action_a
when in state_a
,但连接到action_b
when in state_b
?