我需要能够从不是由用户交互(即通过进程完成)生成的信号(或等效的东西)更改 QStateMachine 的状态。此示例重定向用户生成的信号以演示该想法,但尚未起作用。在这里,按钮信号会触发我想用于转换的其他信号。这里的状态B1 <-> B2
是按下Bi -> Bj
按钮时重定向信号的位置bi
。
QStateMachine 文档似乎只涵盖了基于按钮直接信号的转换,我无法推断出使用任何信号的更一般情况(即我创建的信号)。
import sys
from PySide2.QtCore import Qt, QStateMachine, QState, Signal as QSignal
from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.w = QWidget()
self.setCentralWidget(self.w)
l1 = QVBoxLayout()
self.b1 = QPushButton("B1", self.w)
self.b1.pressed.connect(self.b1Pressed)
l1.addWidget(self.b1)
self.b2 = QPushButton("B2", self.w)
self.b2.pressed.connect(self.b2Pressed)
l1.addWidget(self.b2)
self.w .setLayout(l1)
self.setupStateMachine()
self.show()
def b1Pressed(self):
print("b1 pressed")
self._b1Pressed.emit()
def b2Pressed(self):
print("b2 pressed")
self._b2Pressed.emit()
def setupStateMachine(self):
self._b1Pressed = QSignal()
self._b2Pressed = QSignal()
self.sm = QStateMachine()
self.B1 = QState()
self.B1.assignProperty(self.b1, "enabled", True)
self.B1.assignProperty(self.b2, "enabled", False)
self.sm.addState(self.B1)
self.B2 = QState()
self.B2.assignProperty(self.b1, "enabled", False)
self.B2.assignProperty(self.b2, "enabled", True)
self.sm.addState(self.B2)
# The point of it all:
# change states from a signal (or program generated event)
self.B1.addTransition(self._b1Pressed, self.B2)
self.B2.addTransition(self._b2Pressed, self.B1)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())