Ejemplo n.º 1
0
    def _make_dev_fetched_state(self, form) -> QState:
        s = QState()
        s.assignProperty(form.editBtn, "enabled", True)
        s.assignProperty(form.deviceList, "enabled", True)
        s.assignProperty(form.saveBtn, "enabled", False)
        s.assignProperty(form.addressEdit, "enabled", False)

        return s
Ejemplo n.º 2
0
    def makeState(self, parentState, animationFileName):
        topLevel = QState(parentState)

        animation = Animation()

        file = QFile(animationFileName)
        if file.open(QIODevice.ReadOnly):
            animation.load(file)

        frameCount = animation.totalFrames()
        previousState = None
        for i in range(frameCount):
            animation.setCurrentFrame(i)

            frameState = QState(topLevel)
            nodeCount = animation.nodeCount()
            for j in range(nodeCount):
                frameState.assignProperty(self.m_stickMan.node(j), "pos", animation.nodePos(j))

            frameState.setObjectName("frame %d" % i)

            if previousState is None:
                topLevel.setInitialState(frameState)
            else:
                previousState.addTransition(previousState.propertiesAssigned, frameState)

            previousState = frameState

        previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState())

        return topLevel
Ejemplo n.º 3
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['Замещение торможения'].clicked,
                                 self)

        self.start = Start(self)
        self.ppm = common.Ppm(self)
        self.el_breaking = common.ElBreaking(self)
        self.speed_60 = common.Speed60(self)
        self.ku_215 = common.KU215(self)
        self.pim = common.Pim(self)
        self.enter = common.Enter(state='- 0 -', parent=self)
        self.el_breaking_on = ElBreakingOn(self)
        self.measure = Measure(self)
        self.ok = Ok(self)
        self.ok_measure = OkMeasure(self)
        self.el_breaking_off = ElBreakingOff(self)
        self.show_result = ShowResult(self)

        self.setInitialState(self.start)
        self.start.addTransition(self.ppm)
        self.ppm.addTransition(ctrl.server_updated, self.ppm)
        self.ppm.addTransition(self.ppm.done, self.el_breaking)
        self.el_breaking.addTransition(ctrl.switch['el. braking'].low_value,
                                       self.speed_60)
        self.speed_60.addTransition(ctrl.switch['>60 km/h'].low_value,
                                    self.ku_215)
        self.ku_215.addTransition(ctrl.switch['ku 215'].high_value, self.pim)
        self.pim.addTransition(ctrl.server_updated, self.pim)
        self.pim.addTransition(self.pim.done, self.enter)
        self.enter.addTransition(
            ctrl.switch_with_neutral['enter'].state_neutral,
            self.el_breaking_on)
        self.el_breaking_on.addTransition(ctrl.server_updated,
                                          self.el_breaking_on)
        self.el_breaking_on.addTransition(self.el_breaking_on.done,
                                          self.measure)
        self.measure.addTransition(ctrl.server_updated, self.measure)
        self.measure.addTransition(self.measure.done, self.ok)
        self.ok.addTransition(ctrl.switch['ok'].high_value, self.ok_measure)
        self.ok_measure.addTransition(ctrl.server_updated, self.ok_measure)
        self.ok_measure.addTransition(ctrl.switch['ok'].low_value,
                                      self.el_breaking_off)
        self.el_breaking_off.addTransition(ctrl.server_updated,
                                           self.el_breaking_off)
        self.el_breaking_off.addTransition(self.el_breaking_off.done,
                                           self.show_result)
Ejemplo n.º 4
0
 def createState(self):
     mainState = QState(self.fsm)
     connectedState = QState(QtCore.QState.ParallelStates, mainState)
     processBuyState = QState(connectedState)
     determineBuyProcessBuyState = QState(processBuyState)
     waitingTRlimitProcessBuyState = QState(processBuyState)
     print(determineBuyProcessBuyState)
     determineBuyProcessBuyState.addTransition(self.sigNoBuy, waitingTRlimitProcessBuyState)
     determineBuyProcessBuyState.addTransition(self.sigBuy, waitingTRlimitProcessBuyState)
     self.test_buy()
     determineBuyProcessBuyState.entered.connect(self.determineBuyProcessBuyStateEntered)
Ejemplo n.º 5
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['Повышенная скорость'].clicked,
                                 self)

        self.start = Start(self)
        self.ppm = common.Ppm(self)
        self.el_breaking = common.ElBreaking(self)
        self.speed_60 = common.Speed60(self)
        self.ku_215 = common.KU215(self)
        self.pim = common.Pim(self)
        self.enter = common.Enter(state='- 0 -', parent=self)
        self.speed_on = SpeedOn(self)
        self.measure_fill = MeasureFill(self)

        self.speed_off = SpeedOff(self)
        self.measure_empty = MeasureEmpty(self)
        self.show_result = ShowResult(self)

        self.setInitialState(self.start)
        self.start.addTransition(self.ppm)
        self.ppm.addTransition(ctrl.server_updated, self.ppm)
        self.ppm.addTransition(self.ppm.done, self.ku_215)
        # self.el_breaking.addTransition(ctrl.switch['el. braking'].low_value, self.speed_60)
        # self.speed_60.addTransition(ctrl.switch['>60 km/h'].low_value, self.ku_215)
        self.ku_215.addTransition(ctrl.switch['ku 215'].high_value, self.pim)
        self.pim.addTransition(ctrl.server_updated, self.pim)
        self.pim.addTransition(self.pim.done, self.enter)
        self.enter.addTransition(ctrl.switch_with_neutral['km'].state_neutral,
                                 self.speed_on)
        self.speed_on.addTransition(ctrl.server_updated, self.speed_on)
        self.speed_on.addTransition(self.speed_on.done, self.measure_fill)
        self.measure_fill.addTransition(ctrl.server_updated, self.measure_fill)
        self.measure_fill.addTransition(self.measure_fill.done, self.speed_off)
        self.speed_off.addTransition(ctrl.server_updated, self.speed_off)
        self.speed_off.addTransition(self.speed_off.done, self.measure_empty)
        self.measure_empty.addTransition(ctrl.server_updated,
                                         self.measure_empty)
        self.measure_empty.addTransition(self.measure_empty.done,
                                         self.show_result)
Ejemplo n.º 6
0
def createGeometryState(w1, rect1, w2, rect2, w3, rect3, w4, rect4, parent):
    result = QState(parent)

    result.assignProperty(w1, 'geometry', rect1)
    result.assignProperty(w1, 'geometry', rect1)
    result.assignProperty(w2, 'geometry', rect2)
    result.assignProperty(w3, 'geometry', rect3)
    result.assignProperty(w4, 'geometry', rect4)

    return result
Ejemplo n.º 7
0
    def __init__(self, lcd, targetVal, serial=None, template=None):
        super().__init__()

        self.defaultState = DisplayState(lcd, Color.BLACK, 0.0)
        self.upState = DisplayState(lcd, Color.GREEN)
        self.downState = DisplayState(lcd, Color.RED)
        self.waitState = QState()

        self.setTimer = QTimer()
        self.setTimer.setInterval(DELAY_BEFORE_SET)
        self.setTimer.setSingleShot(True)
        self.waitState.entered.connect(self.setTimer.start)
        self.waitState.exited.connect(self.setTimer.stop)

        for s in [
                self.defaultState, self.upState, self.downState, self.waitState
        ]:
            self.addState(s)
            s.addTransition(self.raiseTarget, self.upState)
            s.addTransition(self.lowerTarget, self.downState)
        for s in [self.upState, self.downState]:
            s.addTransition(s.done, self.waitState)
        self.waitState.addTransition(self.setTimer.timeout, self.defaultState)

        self.setInitialState(self.defaultState)

        self.target = float(targetVal)

        if serial is not None:
            #self.serial = serial
            self.template = template

            serial.newDataAvailable.connect(self.defaultState.updateDisplay)

            self.waitState.exited.connect(self.sendTarget)
            self.sendToSerial.connect(serial.broadcast)

            self.requestTimer = QTimer()
            self.requestTimer.setInterval(REFRESH_PERIOD)
            self.requestTimer.timeout.connect(self.sendRequest)
            self.defaultState.entered.connect(self.requestTimer.start)
            self.defaultState.exited.connect(self.requestTimer.stop)

        self.start()
Ejemplo n.º 8
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['Время снижения'].clicked, self)

        self.start = Start(self)
        self.ppm = common.Ppm(self)
        self.el_breaking = common.ElBreaking(self)
        self.speed_60 = common.Speed60(self)
        self.ku_215 = common.KU215(self)
        self.enter = common.Enter(state='КУ', parent=self)
        self.handle_position_four = common.HandlePositionFour(self)
        self.handle_position_zero = HandlePositionZero(self)
        self.measure = Measure(self)
        self.show_result = ShowResult(self)

        self.setInitialState(self.start)
        self.start.addTransition(self.ppm)
        self.ppm.addTransition(ctrl.server_updated, self.ppm)
        self.ppm.addTransition(self.ppm.done, self.el_breaking)
        self.el_breaking.addTransition(ctrl.switch['el. braking'].low_value,
                                       self.speed_60)
        self.speed_60.addTransition(ctrl.switch['>60 km/h'].low_value,
                                    self.ku_215)
        self.ku_215.addTransition(ctrl.switch['ku 215'].high_value, self.enter)
        self.enter.addTransition(ctrl.switch_with_neutral['enter'].state_two,
                                 self.handle_position_four)
        self.handle_position_four.addTransition(ctrl.server_updated,
                                                self.handle_position_four)
        self.handle_position_four.addTransition(self.handle_position_four.done,
                                                self.handle_position_zero)
        self.handle_position_zero.addTransition(ctrl.server_updated,
                                                self.handle_position_zero)
        self.handle_position_zero.addTransition(self.handle_position_zero.done,
                                                self.measure)
        self.measure.addTransition(ctrl.server_updated, self.measure)
        self.measure.addTransition(self.measure.done, self.show_result)
Ejemplo n.º 9
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common: Common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        menu = ctrl.menu.menu['БТП 020']
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu_state.addTransition(menu.button['Подготовка'].clicked, self)

        self.start = Start(self)
        self.ppm = common.Ppm(self)
        self.install_ku = InstallKU(self)
        self.ku_215 = common.KU215(self)
        self.pim = common.Pim(self)
        self.tank = common.Tank(state='СБРОС', parent=self)
        self.el_breaking = common.ElBreaking(self)
        self.speed_60 = common.Speed60(self)
        self.set_bto = SetBTO(self)
        self.connect_btp = ConnectBTP(self)
        self.enable_menu = EnableMenu(self)

        self.setInitialState(self.start)
        self.start.addTransition(self.install_ku)
        self.install_ku.addTransition(ctrl.button['yes'].clicked, self.ku_215)
        self.ku_215.addTransition(ctrl.switch['ku 215'].high_value, self.ppm)
        self.ppm.addTransition(ctrl.server_updated, self.ppm)
        self.ppm.addTransition(self.ppm.done, self.pim)
        self.pim.addTransition(ctrl.server_updated, self.pim)
        self.pim.addTransition(self.pim.done, self.tank)
        self.tank.addTransition(ctrl.switch_with_neutral['tank'].state_two,
                                self.el_breaking)
        self.el_breaking.addTransition(ctrl.switch['el. braking'].low_value,
                                       self.speed_60)
        self.speed_60.addTransition(ctrl.switch['>60 km/h'].low_value,
                                    self.set_bto)
        self.set_bto.addTransition(ctrl.button['yes'].clicked,
                                   self.connect_btp)
        self.connect_btp.addTransition(ctrl.button['yes'].clicked,
                                       self.enable_menu)
        self.enable_menu.addTransition(self.finish)
Ejemplo n.º 10
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['Герметичность'].clicked, self)

        self.start = Start(self)
        self.ppm = common.Ppm(self)
        self.el_breaking = common.ElBreaking(self)
        self.speed_60 = common.Speed60(self)
        self.ku_215 = common.KU215(self)
        self.enter = common.Enter(state='КУ', parent=self)
        self.handle_position_four = common.HandlePositionFour(self)
        self.check = Check(self)
        self.yes = Yes(self)
        self.no = No(self)

        self.setInitialState(self.start)
        self.start.addTransition(self.ppm)
        self.ppm.addTransition(ctrl.server_updated, self.ppm)
        self.ppm.addTransition(self.ppm.done, self.el_breaking)
        self.el_breaking.addTransition(ctrl.switch['el. braking'].low_value,
                                       self.speed_60)
        self.speed_60.addTransition(ctrl.switch['>60 km/h'].low_value,
                                    self.ku_215)
        self.ku_215.addTransition(ctrl.switch['ku 215'].high_value, self.enter)
        self.enter.addTransition(ctrl.switch_with_neutral['enter'].state_two,
                                 self.handle_position_four)
        self.handle_position_four.addTransition(ctrl.server_updated,
                                                self.handle_position_four)
        self.handle_position_four.addTransition(self.handle_position_four.done,
                                                self.check)
        self.check.addTransition(ctrl.button['yes'].clicked, self.yes)
        self.check.addTransition(ctrl.button['no'].clicked, self.no)
        self.yes.addTransition(self.finish)
        self.no.addTransition(self.finish)
Ejemplo n.º 11
0
    def createGeometryState(self, w1, rect1, w2, rect2, w3, rect3, w4, rect4, parent):
        result = QState(parent)

        result.assignProperty(w1, 'geometry', rect1)
        result.assignProperty(w1, 'geometry', rect1)
        result.assignProperty(w2, 'geometry', rect2)
        result.assignProperty(w3, 'geometry', rect3)
        result.assignProperty(w4, 'geometry', rect4)

        return result
Ejemplo n.º 12
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['Завершение'].clicked, self)

        self.start = Start(self)
        self.air = Air(self)
        self.ku_215_off = KU215Off(self)
        self.disconnect_bto = DisconnectBTO(self)
        self.report = Report(parent=self, controller=controller)

        self.setInitialState(self.start)
        self.start.addTransition(self.air)
        self.air.addTransition(ctrl.button['yes'].clicked, self.ku_215_off)
        self.ku_215_off.addTransition(ctrl.switch['ku 215'].low_value,
                                      self.disconnect_bto)
        self.disconnect_bto.addTransition(ctrl.button['yes'].clicked,
                                          self.report)
Ejemplo n.º 13
0
    def __init__(self, controller: Controller, menu: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu)
        self.reset = Reset(self)
        self.disable_menu = DisableMenu(self)
        self.report_data = ReportData(self)
        self.menu = Menu(self)
        menu.addTransition(
            ctrl.menu.menu['Главное меню'].button['БТП 020'].clicked, self)

        self.setInitialState(self.reset)
        self.reset.addTransition(self.disable_menu)
        self.disable_menu.addTransition(self.report_data)
        self.report_data.addTransition(ctrl.button['back'].clicked,
                                       self.finish)
        self.report_data.addTransition(ctrl.menu.prepare_menu.done.clicked,
                                       self.menu)
        self.menu.addTransition(ctrl.button['back'].clicked, self.finish)

        self.prepare = Prepare(controller=ctrl, menu_state=self.menu)
        self.auto_breaking = AutoBreaking(controller=ctrl,
                                          menu_state=self.menu)
        self.kvt_breaking = KvtBreaking(controller=ctrl, menu_state=self.menu)
        self.filling = Filling(controller=ctrl, menu_state=self.menu)
        self.tightness = Tightness(controller=ctrl, menu_state=self.menu)
        self.emptying = Emptying(controller=ctrl, menu_state=self.menu)
        self.substitution = Substitution(controller=ctrl, menu_state=self.menu)
        self.speed = Speed(controller=ctrl, menu_state=self.menu)
        self.ending = Ending(controller=ctrl, menu_state=self.menu)

        self.ending.report.addTransition(ctrl.report.exit.clicked, self.finish)
        self.ending.report.addTransition(ctrl.button['back'].clicked,
                                         self.finish)
Ejemplo n.º 14
0
    def __init__(self, controller: Controller, menu_state: QState):
        super().__init__(parent=controller.stm)
        global ctrl
        ctrl = controller
        common = Common(controller=ctrl)
        self.finish = QFinalState(self)
        self.addTransition(self.finished, menu_state)
        self.addTransition(ctrl.button['back'].clicked, self.finish)
        menu = ctrl.menu.menu['БТП 020']
        menu_state.addTransition(menu.button['торможение автоматическое'].clicked, self)

        self.start = Start(self)
        self.pim = common.Pim(self)
        self.check_1 = Check(stage=0, parent=self)
        self.check_2 = Check(stage=1, parent=self)
        self.check_3 = Check(stage=2, parent=self)
        self.check_4 = Check(stage=3, parent=self)
        self.check_5 = Check(stage=4, parent=self)
        self.check_6 = Check(stage=5, parent=self)
        self.check_7 = Check(stage=6, parent=self)
        self.check_8 = Check(stage=7, parent=self)
        self.show_result = ShowResult(parent=self)

        self.setInitialState(self.start)
        self.start.addTransition(self.pim)
        self.pim.addTransition(ctrl.server_updated, self.pim)
        self.pim.addTransition(self.pim.done, self.check_1)
        self.check_1.addTransition(self.check_1.finished, self.check_2)
        self.check_2.addTransition(self.check_2.finished, self.check_3)
        self.check_3.addTransition(self.check_3.finished, self.check_4)
        self.check_4.addTransition(self.check_4.finished, self.check_5)
        self.check_5.addTransition(self.check_5.finished, self.check_6)
        self.check_6.addTransition(self.check_6.finished, self.check_7)
        self.check_7.addTransition(self.check_7.finished, self.check_8)
        self.check_8.addTransition(self.check_8.finished, self.show_result)
        self.show_result.addTransition(ctrl.button['yes'].clicked, self.finish)
Ejemplo n.º 15
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setAttribute(Qt.WA_QuitOnClose)
        self.setAttribute(Qt.WA_DeleteOnClose)

        # create instance variables
        self._ui = uic.loadUi('mainwindow.ui', self)

        # create models
        self.measureModels = {
            1: MeasureModel(self),
            2: MeasureModel(self),
        }
        self._instrumentManager = InstrumentManager(self, self.measureModels)

        self.machine = QStateMachine()
        self.stateInitial = QState()
        self.stateReadyToCheck = QState()
        self.stateReadyToMeasure = QState()
        self.stateAfterMeasure = QState()

        self.initDialog()
Ejemplo n.º 16
0
    def Home(self):
        self.items = []
        for i in range(len(self.names['home'])):
            item = QPushButton(self)
            item.setText(self.names['home'][i])
            item.setGeometry(395, 350, 120, 80)
            item.setStyleSheet(
                "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n"
                "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n"
                "")
            self.font.setPointSize(15)
            item.setFont(self.font)
            self.items.append(item)
            exec("""item.clicked.connect(partial(self.IND,i=%i))""" % (i))

        self.rootState = QState()
        self.tiledState = QState(self.rootState)
        self.centeredState = QState(self.rootState)
        for i, item in enumerate(self.items):
            self.tiledState.assignProperty(
                item, 'pos',
                QPointF(((i % 6) * 5.3) * 30, ((i // 6) * 5.3) * 30))

            self.centeredState.assignProperty(item, 'pos', QPointF())

        self.states = QStateMachine()
        self.states.addState(self.rootState)
        self.states.setInitialState(self.rootState)
        self.rootState.setInitialState(self.centeredState)
        self.group = QParallelAnimationGroup()
        for i, item in enumerate(self.items):
            anim = QPropertyAnimation(item, b'pos')
            anim.setStartValue(QPoint(400, 300))
            anim.setDuration(750 + i * 25)
            anim.setEasingCurve(QEasingCurve.InOutBack)
            self.group.addAnimation(anim)

        for u in self.items:
            trans = self.rootState.addTransition(u.clicked, self.tiledState)
            trans.addAnimation(self.group)
            self.states.start()
Ejemplo n.º 17
0
    def __init__(self, blaster, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.offState = QState()
        self.revState = QState()
        self.onState = QState()

        for s in [self.offState, self.revState, self.onState]:
            self.addState(s)
        self.setInitialState(self.offState)

        self.offState.entered.connect(lambda: blaster.triggerStateChange(3))
        self.offState.exited.connect(lambda: blaster.triggerStateChange(0))
        self.onState.entered.connect(lambda: blaster.triggerStateChange(1))
        self.onState.exited.connect(lambda: blaster.triggerStateChange(2))

        self.spinUp = QSignalTransition(self.touched)
        self.spinUp.setTargetState(self.revState)
        self.spinDown = QSignalTransition(self.letGo)
        self.spinDown.setTargetState(self.offState)
        self.revState.addTransition(self.pressed, self.onState)
        self.onState.addTransition(self.released, self.revState)

        self.start()
Ejemplo n.º 18
0
    def __init__(self, size, parent=None):
        super(PadNavigator, self).__init__(parent)

        self.form = Ui_Form()

        splash = SplashItem()
        splash.setZValue(1)

        pad = FlippablePad(size)
        flipRotation = QGraphicsRotation(pad)
        xRotation = QGraphicsRotation(pad)
        yRotation = QGraphicsRotation(pad)
        flipRotation.setAxis(Qt.YAxis)
        xRotation.setAxis(Qt.YAxis)
        yRotation.setAxis(Qt.XAxis)
        pad.setTransformations([flipRotation, xRotation, yRotation])

        backItem = QGraphicsProxyWidget(pad)
        widget = QWidget()
        self.form.setupUi(widget)
        self.form.hostName.setFocus()
        backItem.setWidget(widget)
        backItem.setVisible(False)
        backItem.setFocus()
        backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        r = backItem.rect()
        backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate(
            -r.width() / 2, -r.height() / 2))

        selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120),
                                      QColor(Qt.gray), pad)
        selectionItem.setZValue(0.5)

        smoothSplashMove = QPropertyAnimation(splash)
        smoothSplashOpacity = QPropertyAnimation(splash)
        smoothSplashMove.setEasingCurve(QEasingCurve.InQuad)
        smoothSplashMove.setDuration(250)
        smoothSplashOpacity.setDuration(250)

        smoothXSelection = QPropertyAnimation(selectionItem)
        smoothYSelection = QPropertyAnimation(selectionItem)
        smoothXRotation = QPropertyAnimation(xRotation)
        smoothYRotation = QPropertyAnimation(yRotation)
        smoothXSelection.setDuration(125)
        smoothYSelection.setDuration(125)
        smoothXRotation.setDuration(125)
        smoothYRotation.setDuration(125)
        smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad)

        smoothFlipRotation = QPropertyAnimation(flipRotation)
        smoothFlipScale = QPropertyAnimation(pad)
        smoothFlipXRotation = QPropertyAnimation(xRotation)
        smoothFlipYRotation = QPropertyAnimation(yRotation)
        flipAnimation = QParallelAnimationGroup(self)
        smoothFlipScale.setDuration(500)
        smoothFlipRotation.setDuration(500)
        smoothFlipXRotation.setDuration(500)
        smoothFlipYRotation.setDuration(500)
        smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipScale.setKeyValueAt(0, 1.0)
        smoothFlipScale.setKeyValueAt(0.5, 0.7)
        smoothFlipScale.setKeyValueAt(1, 1.0)
        flipAnimation.addAnimation(smoothFlipRotation)
        flipAnimation.addAnimation(smoothFlipScale)
        flipAnimation.addAnimation(smoothFlipXRotation)
        flipAnimation.addAnimation(smoothFlipYRotation)

        setVariablesSequence = QSequentialAnimationGroup()
        setFillAnimation = QPropertyAnimation(pad)
        setBackItemVisibleAnimation = QPropertyAnimation(backItem)
        setSelectionItemVisibleAnimation = QPropertyAnimation(selectionItem)
        setFillAnimation.setDuration(0)
        setBackItemVisibleAnimation.setDuration(0)
        setSelectionItemVisibleAnimation.setDuration(0)
        setVariablesSequence.addPause(250)
        setVariablesSequence.addAnimation(setBackItemVisibleAnimation)
        setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation)
        setVariablesSequence.addAnimation(setFillAnimation)
        flipAnimation.addAnimation(setVariablesSequence)

        stateMachine = QStateMachine(self)
        splashState = QState(stateMachine)
        frontState = QState(stateMachine)
        historyState = QHistoryState(frontState)
        backState = QState(stateMachine)

        frontState.assignProperty(pad, "fill", False)
        frontState.assignProperty(splash, "opacity", 0.0)
        frontState.assignProperty(backItem, "visible", False)
        frontState.assignProperty(flipRotation, "angle", 0.0)
        frontState.assignProperty(selectionItem, "visible", True)

        backState.assignProperty(pad, "fill", True)
        backState.assignProperty(backItem, "visible", True)
        backState.assignProperty(xRotation, "angle", 0.0)
        backState.assignProperty(yRotation, "angle", 0.0)
        backState.assignProperty(flipRotation, "angle", 180.0)
        backState.assignProperty(selectionItem, "visible", False)

        stateMachine.addDefaultAnimation(smoothXRotation)
        stateMachine.addDefaultAnimation(smoothYRotation)
        stateMachine.addDefaultAnimation(smoothXSelection)
        stateMachine.addDefaultAnimation(smoothYSelection)
        stateMachine.setInitialState(splashState)

        anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState)
        anyKeyTransition.setTargetState(frontState)
        anyKeyTransition.addAnimation(smoothSplashMove)
        anyKeyTransition.addAnimation(smoothSplashOpacity)

        enterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                              Qt.Key_Enter, backState)
        returnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                               Qt.Key_Return, backState)
        backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                  Qt.Key_Enter, frontState)
        backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                   Qt.Key_Return, frontState)
        enterTransition.setTargetState(historyState)
        returnTransition.setTargetState(historyState)
        backEnterTransition.setTargetState(backState)
        backReturnTransition.setTargetState(backState)
        enterTransition.addAnimation(flipAnimation)
        returnTransition.addAnimation(flipAnimation)
        backEnterTransition.addAnimation(flipAnimation)
        backReturnTransition.addAnimation(flipAnimation)

        columns = size.width()
        rows = size.height()
        stateGrid = []
        for y in range(rows):
            stateGrid.append([QState(frontState) for _ in range(columns)])

        frontState.setInitialState(stateGrid[0][0])
        selectionItem.setPos(pad.iconAt(0, 0).pos())

        for y in range(rows):
            for x in range(columns):
                state = stateGrid[y][x]

                rightTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                      Qt.Key_Right, state)
                leftTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                     Qt.Key_Left, state)
                downTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                     Qt.Key_Down, state)
                upTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                   Qt.Key_Up, state)

                rightTransition.setTargetState(stateGrid[y][(x + 1) % columns])
                leftTransition.setTargetState(
                    stateGrid[y][((x - 1) + columns) % columns])
                downTransition.setTargetState(stateGrid[(y + 1) % rows][x])
                upTransition.setTargetState(stateGrid[((y - 1) + rows) %
                                                      rows][x])

                icon = pad.iconAt(x, y)
                state.assignProperty(xRotation, "angle", -icon.x() / 6.0)
                state.assignProperty(yRotation, "angle", icon.y() / 6.0)
                state.assignProperty(selectionItem, "x", icon.x())
                state.assignProperty(selectionItem, "y", icon.y())
                frontState.assignProperty(icon, "visible", True)
                backState.assignProperty(icon, "visible", False)

                setIconVisibleAnimation = QPropertyAnimation(icon)
                setIconVisibleAnimation.setDuration(0)
                setVariablesSequence.addAnimation(setIconVisibleAnimation)

        scene = QGraphicsScene(self)
        scene.setBackgroundBrush(
            QBrush(QPixmap(":/images/blue_angle_swirl.jpg")))
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.addItem(pad)
        scene.setSceneRect(scene.itemsBoundingRect())
        self.setScene(scene)

        sbr = splash.boundingRect()
        splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2)
        frontState.assignProperty(splash, "y", splash.y() - 100.0)
        scene.addItem(splash)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMinimumSize(50, 50)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHints(QPainter.Antialiasing
                            | QPainter.SmoothPixmapTransform
                            | QPainter.TextAntialiasing)

        if QGLFormat.hasOpenGL():
            self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))

        stateMachine.start()
Ejemplo n.º 19
0
    tiledButton = Button(QPixmap(':/images/tile.png'), buttonParent)
    centeredButton = Button(QPixmap(':/images/centered.png'), buttonParent)

    ellipseButton.setPos(-100, -100)
    figure8Button.setPos(100, -100)
    randomButton.setPos(0, 0)
    tiledButton.setPos(-100, 100)
    centeredButton.setPos(100, 100)

    scene.addItem(buttonParent)
    buttonParent.setScale(0.75)
    buttonParent.setPos(200, 200)
    buttonParent.setZValue(65)

    # States.
    rootState = QState()
    ellipseState = QState(rootState)
    figure8State = QState(rootState)
    randomState = QState(rootState)
    tiledState = QState(rootState)
    centeredState = QState(rootState)

    # Values.
    for i, item in enumerate(items):
        # Ellipse.
        ellipseState.assignProperty(item, 'pos',
                QPointF(math.cos((i / 63.0) * 6.28) * 250,
                        math.sin((i / 63.0) * 6.28) * 250))

        # Figure 8.
        figure8State.assignProperty(item, 'pos',
Ejemplo n.º 20
0
    p5 = Pixmap(QPixmap(':/help-browser.png'))
    p6 = Pixmap(QPixmap(':/kchart.png'))

    scene = QGraphicsScene(0, 0, 400, 300)
    scene.setBackgroundBrush(scene.palette().window())
    scene.addItem(widget)
    scene.addItem(boxProxy)
    scene.addItem(p1)
    scene.addItem(p2)
    scene.addItem(p3)
    scene.addItem(p4)
    scene.addItem(p5)
    scene.addItem(p6)

    machine = QStateMachine()
    state1 = QState(machine)
    state2 = QState(machine)
    state3 = QState(machine)
    machine.setInitialState(state1)

    # State 1.
    state1.assignProperty(button, 'text', "Switch to state 2")
    state1.assignProperty(widget, 'geometry', QRectF(0, 0, 400, 150))
    state1.assignProperty(box, 'geometry', QRect(-200, 150, 200, 150))
    state1.assignProperty(p1, 'pos', QPointF(68, 185))
    state1.assignProperty(p2, 'pos', QPointF(168, 185))
    state1.assignProperty(p3, 'pos', QPointF(268, 185))
    state1.assignProperty(p4, 'pos', QPointF(68 - 150, 48 - 150))
    state1.assignProperty(p5, 'pos', QPointF(168, 48 - 150))
    state1.assignProperty(p6, 'pos', QPointF(268 + 150, 48 - 150))
    state1.assignProperty(p1, 'rotation', 0.0)
Ejemplo n.º 21
0
    tiledButton = Button(QPixmap(':/images/tile.png'), buttonParent)
    centeredButton = Button(QPixmap(':/images/centered.png'), buttonParent)

    ellipseButton.setPos(-100, -100)
    figure8Button.setPos(100, -100)
    randomButton.setPos(0, 0)
    tiledButton.setPos(-100, 100)
    centeredButton.setPos(100, 100)

    scene.addItem(buttonParent)
    buttonParent.setScale(0.75)
    buttonParent.setPos(200, 200)
    buttonParent.setZValue(65)

    # States.
    rootState = QState()
    ellipseState = QState(rootState)
    figure8State = QState(rootState)
    randomState = QState(rootState)
    tiledState = QState(rootState)
    centeredState = QState(rootState)

    # Values.
    for i, item in enumerate(items):
        # Ellipse.
        ellipseState.assignProperty(
            item, 'pos',
            QPointF(
                math.cos((i / 63.0) * 6.28) * 250,
                math.sin((i / 63.0) * 6.28) * 250))
Ejemplo n.º 22
0
    #tr = QScxmlSignalTransition(pb.clicked)

    scxml_machine = QScxml()
    scxml_machine.registerObject(pb, "pb")
    scxml_machine.registerObject(cb, "cb")
    scxml_machine.load("test144.scxml")
    #scxml_machine = QScxml.load("ExifMediaRename.scxml", )

    scxml_machine.start()



    if 0:
        sm = QStateMachine()
        s1 = QState()

        s2 = QState()
        s2.entered.connect(toto)

        st = QSignalTransition(pb.clicked)
        st.setTargetState(s2)

        s1.addTransition(st)
        sm.addState(s1)
        sm.addState(s2)
        sm.setInitialState(s1)
        sm.start()

    sys.exit(app.exec_())
Ejemplo n.º 23
0
    scene = QGraphicsScene(0, 0, 300, 300)
    scene.setBackgroundBrush(Qt.black)
    scene.addItem(button1)
    scene.addItem(button2)
    scene.addItem(button3)
    scene.addItem(button4)

    window = QGraphicsView(scene)
    window.setFrameStyle(0)
    window.setAlignment(Qt.AlignLeft | Qt.AlignTop)
    window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    machine = QStateMachine()

    group = QState()
    timer = QTimer()
    timer.setInterval(1250)
    timer.setSingleShot(True)
    group.entered.connect(timer.start)

    state1 = createGeometryState(button1, QRect(100, 0, 50, 50), button2,
            QRect(150, 0, 50, 50), button3, QRect(200, 0, 50, 50), button4,
            QRect(250, 0, 50, 50), group)

    state2 = createGeometryState(button1, QRect(250, 100, 50, 50), button2,
            QRect(250, 150, 50, 50), button3, QRect(250, 200, 50, 50), button4,
            QRect(250, 250, 50, 50), group)

    state3 = createGeometryState(button1, QRect(150, 250, 50, 50), button2,
            QRect(100, 250, 50, 50), button3, QRect(50, 250, 50, 50), button4,
Ejemplo n.º 24
0
    def __init__(self, size, parent=None):
        super(PadNavigator, self).__init__(parent)

        self.form = Ui_Form()

        splash = SplashItem()
        splash.setZValue(1)

        pad = FlippablePad(size)
        flipRotation = QGraphicsRotation(pad)
        xRotation = QGraphicsRotation(pad)
        yRotation = QGraphicsRotation(pad)
        flipRotation.setAxis(Qt.YAxis)
        xRotation.setAxis(Qt.YAxis)
        yRotation.setAxis(Qt.XAxis)
        pad.setTransformations([flipRotation, xRotation, yRotation])

        backItem = QGraphicsProxyWidget(pad)
        widget = QWidget()
        self.form.setupUi(widget)
        self.form.hostName.setFocus()
        backItem.setWidget(widget)
        backItem.setVisible(False)
        backItem.setFocus()
        backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        r = backItem.rect()
        backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate(-r.width()/2, -r.height()/2))

        selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120),
                QColor(Qt.gray), pad)
        selectionItem.setZValue(0.5)

        smoothSplashMove = QPropertyAnimation(splash, b'y')
        smoothSplashOpacity = QPropertyAnimation(splash, b'opacity')
        smoothSplashMove.setEasingCurve(QEasingCurve.InQuad)
        smoothSplashMove.setDuration(250)
        smoothSplashOpacity.setDuration(250)

        smoothXSelection = QPropertyAnimation(selectionItem, b'x')
        smoothYSelection = QPropertyAnimation(selectionItem, b'y')
        smoothXRotation = QPropertyAnimation(xRotation, b'angle')
        smoothYRotation = QPropertyAnimation(yRotation, b'angle')
        smoothXSelection.setDuration(125)
        smoothYSelection.setDuration(125)
        smoothXRotation.setDuration(125)
        smoothYRotation.setDuration(125)
        smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad)

        smoothFlipRotation = QPropertyAnimation(flipRotation, b'angle')
        smoothFlipScale = QPropertyAnimation(pad, b'scale')
        smoothFlipXRotation = QPropertyAnimation(xRotation, b'angle')
        smoothFlipYRotation = QPropertyAnimation(yRotation, b'angle')
        flipAnimation = QParallelAnimationGroup(self)
        smoothFlipScale.setDuration(500)
        smoothFlipRotation.setDuration(500)
        smoothFlipXRotation.setDuration(500)
        smoothFlipYRotation.setDuration(500)
        smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipScale.setKeyValueAt(0, 1.0)
        smoothFlipScale.setKeyValueAt(0.5, 0.7)
        smoothFlipScale.setKeyValueAt(1, 1.0)
        flipAnimation.addAnimation(smoothFlipRotation)
        flipAnimation.addAnimation(smoothFlipScale)
        flipAnimation.addAnimation(smoothFlipXRotation)
        flipAnimation.addAnimation(smoothFlipYRotation)

        setVariablesSequence = QSequentialAnimationGroup()
        setFillAnimation = QPropertyAnimation(pad, b'fill')
        setBackItemVisibleAnimation = QPropertyAnimation(backItem, b'visible')
        setSelectionItemVisibleAnimation = QPropertyAnimation(selectionItem, b'visible')
        setFillAnimation.setDuration(0)
        setBackItemVisibleAnimation.setDuration(0)
        setSelectionItemVisibleAnimation.setDuration(0)
        setVariablesSequence.addPause(250)
        setVariablesSequence.addAnimation(setBackItemVisibleAnimation)
        setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation)
        setVariablesSequence.addAnimation(setFillAnimation)
        flipAnimation.addAnimation(setVariablesSequence)

        stateMachine = QStateMachine(self)
        splashState = QState(stateMachine)
        frontState = QState(stateMachine)
        historyState = QHistoryState(frontState)
        backState = QState(stateMachine)

        frontState.assignProperty(pad, "fill", False)
        frontState.assignProperty(splash, "opacity", 0.0)
        frontState.assignProperty(backItem, "visible", False)
        frontState.assignProperty(flipRotation, "angle", 0.0)
        frontState.assignProperty(selectionItem, "visible", True)

        backState.assignProperty(pad, "fill", True)
        backState.assignProperty(backItem, "visible", True)
        backState.assignProperty(xRotation, "angle", 0.0)
        backState.assignProperty(yRotation, "angle", 0.0)
        backState.assignProperty(flipRotation, "angle", 180.0)
        backState.assignProperty(selectionItem, "visible", False)

        stateMachine.addDefaultAnimation(smoothXRotation)
        stateMachine.addDefaultAnimation(smoothYRotation)
        stateMachine.addDefaultAnimation(smoothXSelection)
        stateMachine.addDefaultAnimation(smoothYSelection)
        stateMachine.setInitialState(splashState)

        anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState)
        anyKeyTransition.setTargetState(frontState)
        anyKeyTransition.addAnimation(smoothSplashMove)
        anyKeyTransition.addAnimation(smoothSplashOpacity)

        enterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, backState)
        returnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, backState)
        backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, frontState)
        backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, frontState)
        enterTransition.setTargetState(historyState)
        returnTransition.setTargetState(historyState)
        backEnterTransition.setTargetState(backState)
        backReturnTransition.setTargetState(backState)
        enterTransition.addAnimation(flipAnimation)
        returnTransition.addAnimation(flipAnimation)
        backEnterTransition.addAnimation(flipAnimation)
        backReturnTransition.addAnimation(flipAnimation)

        columns = size.width()
        rows = size.height()
        stateGrid = []
        for y in range(rows):
            stateGrid.append([QState(frontState) for _ in range(columns)])

        frontState.setInitialState(stateGrid[0][0])
        selectionItem.setPos(pad.iconAt(0, 0).pos())

        for y in range(rows):
            for x in range(columns):
                state = stateGrid[y][x]

                rightTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Right, state)
                leftTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Left, state)
                downTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Down, state)
                upTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Up, state)

                rightTransition.setTargetState(stateGrid[y][(x + 1) % columns])
                leftTransition.setTargetState(stateGrid[y][((x - 1) + columns) % columns])
                downTransition.setTargetState(stateGrid[(y + 1) % rows][x])
                upTransition.setTargetState(stateGrid[((y - 1) + rows) % rows][x])

                icon = pad.iconAt(x, y)
                state.assignProperty(xRotation, "angle", -icon.x() / 6.0)
                state.assignProperty(yRotation, "angle", icon.y() / 6.0)
                state.assignProperty(selectionItem, "x", icon.x())
                state.assignProperty(selectionItem, "y", icon.y())
                frontState.assignProperty(icon, "visible", True)
                backState.assignProperty(icon, "visible", False)

                setIconVisibleAnimation = QPropertyAnimation(icon, b'visible')
                setIconVisibleAnimation.setDuration(0)
                setVariablesSequence.addAnimation(setIconVisibleAnimation)

        scene = QGraphicsScene(self)
        scene.setBackgroundBrush(QBrush(QPixmap(":/images/blue_angle_swirl.jpg")))
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.addItem(pad)
        scene.setSceneRect(scene.itemsBoundingRect())
        self.setScene(scene)

        sbr = splash.boundingRect()
        splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2)
        frontState.assignProperty(splash, "y", splash.y() - 100.0)
        scene.addItem(splash)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMinimumSize(50, 50)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHints(QPainter.Antialiasing |
                QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)

        if QGLFormat.hasOpenGL():
            self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))

        stateMachine.start()
Ejemplo n.º 25
0
    def __init__(self, parent):
        super(DrawLotteryView, self).__init__()
        self.pwindow = parent   #获取父窗口指针

        self.states = QStateMachine()

        sinitinfo = QState()
        sltypeinfo = QState()
        sprizeinfo = QState()
        svnumberwindow = QState()
        sdrawlottery = QState()
        sfinal = QState()

        sinitinfo.addTransition(self.on_nextstep_event, sltypeinfo)
        sltypeinfo.addTransition(self.on_nextstep_event, sprizeinfo)
        sprizeinfo.addTransition(self.on_nextstep_event, svnumberwindow)
        svnumberwindow.addTransition(self.on_nextstep_event, sdrawlottery)
        sdrawlottery.addTransition(self.on_nextstep_event, sfinal)
        sfinal.addTransition(self.on_final_event, sinitinfo)

        sinitinfo.entered.connect(self.initinfo)
        sltypeinfo.entered.connect(self.viewltypeinfo)
        sprizeinfo.entered.connect(self.viewprizeinfo)
        svnumberwindow.entered.connect(self.viewnumberwindow)
        sdrawlottery.entered.connect(self.drawlottery)
        sfinal.entered.connect(self.final)

        self.states.addState(sinitinfo)
        self.states.addState(sltypeinfo)
        self.states.addState(sprizeinfo)
        self.states.addState(svnumberwindow)
        self.states.addState(sdrawlottery)
        self.states.addState(sfinal)
        self.states.setInitialState(sinitinfo)

        self.states.start()
Ejemplo n.º 26
0
class FeedbackDisplay(QStateMachine):
    """CLASS: FeedbackDisplay
    
    This class wraps a QStateMachine and a QLCDNumber in the GUI so it can keep track of a target value and prevent competing display changes.
    
    SIGNALS                                 SLOTS
    ---------------------    --------------------
    lowerTarget        ()    (float) changeTarget
    raiseTarget        ()    ()       sendRequest
    sendToSerial    (str)    ()        sendTarget
    targetChanged (float)
    """

    targetChanged = pyqtSignal(float)
    """SIGNAL: targetChanged
    
    Emitted when the target value has changed
    
    Broadcasts:
        float - The new target value
    
    Connects to:
        TODO: (probably necessary for FPS)
    """

    raiseTarget = pyqtSignal()
    """SIGNAL: raiseTarget
            
    Internal state change signal
            
    Broadcasts:
        none
            
    Connects to:
        stateMachine transition (* -> upState)
    """

    lowerTarget = pyqtSignal()
    """SIGNAL: lowerTarget
            
    Internal state change signal
            
    Broadcasts:
        none
            
    Connects to:
        stateMachine transition (* -> downState)
    """

    sendToSerial = pyqtSignal(str)
    """SIGNAL: sendToSerial
            
    Delivers a message to be sent over serial
            
    Broadcasts:
        str - The message being sent
            
    Connects to:
        MetroMini.broadcast
    """
    def __init__(self, lcd, targetVal, serial=None, template=None):
        super().__init__()

        self.defaultState = DisplayState(lcd, Color.BLACK, 0.0)
        self.upState = DisplayState(lcd, Color.GREEN)
        self.downState = DisplayState(lcd, Color.RED)
        self.waitState = QState()

        self.setTimer = QTimer()
        self.setTimer.setInterval(DELAY_BEFORE_SET)
        self.setTimer.setSingleShot(True)
        self.waitState.entered.connect(self.setTimer.start)
        self.waitState.exited.connect(self.setTimer.stop)

        for s in [
                self.defaultState, self.upState, self.downState, self.waitState
        ]:
            self.addState(s)
            s.addTransition(self.raiseTarget, self.upState)
            s.addTransition(self.lowerTarget, self.downState)
        for s in [self.upState, self.downState]:
            s.addTransition(s.done, self.waitState)
        self.waitState.addTransition(self.setTimer.timeout, self.defaultState)

        self.setInitialState(self.defaultState)

        self.target = float(targetVal)

        if serial is not None:
            #self.serial = serial
            self.template = template

            serial.newDataAvailable.connect(self.defaultState.updateDisplay)

            self.waitState.exited.connect(self.sendTarget)
            self.sendToSerial.connect(serial.broadcast)

            self.requestTimer = QTimer()
            self.requestTimer.setInterval(REFRESH_PERIOD)
            self.requestTimer.timeout.connect(self.sendRequest)
            self.defaultState.entered.connect(self.requestTimer.start)
            self.defaultState.exited.connect(self.requestTimer.stop)

        self.start()

    def getTarget(self):
        """METHOD: getTarget
    
        Access method for the current target value
    
        Called by:
            DisplayState.onEntry
    
        Arguments:
            none
    
        Returns:
            float - The current target value
        """
        return self.target

    def changeTarget(self, delta):
        """SLOT: changeTarget
    
        Applies a numeric change to the stored target value and directs the QLCDNumber to show that change.
    
        Expects:
            float: The amount by which to shift the target value
    
        Connects to:
            QPushButton.clicked (MainWindow.fpsUpButton, MainWindow.fpsDownButton, MainWindow.psiUpButton, MainWindow.psiDownButton)
            
        Emits:
            raiseTarget, lowerTarget, targetChanged
        """
        self.target += float(delta)
        if delta > 0:
            self.raiseTarget.emit()
        elif delta < 0:
            self.lowerTarget.emit()
        self.targetChanged.emit(self.target)

    def sendRequest(self):
        """SLOT: sendRequest
                
        Sends a serial message requesting a new value from the Metro Mini. Eliminates the need for lambda.
                
        Expects:
            none
                
        Connects to:
            (MainWindow.psiDisplay) QTimer.timeout (requestTimer)
        
        Emits:
            sendToSerial
        """
        self.sendToSerial.emit("request;")

    def sendTarget(self):
        """SLOT: sendTarget
                
        Sends a serial message with a new target value to the Metro Mini. Eliminates the need for lambda.
                
        Expects:
            none
                
        Connects to:
            (MainWindow.psiDisplay) QState.exited (waitState)
        
        Called by:
            MainWindow.initializeSerialObjects
        
        Emits:
            sendToSerial
        """
        self.sendToSerial.emit(self.template.format(self.target))
Ejemplo n.º 27
0
    scene.setBackgroundBrush(Qt.white)
    scene.addItem(p1)
    scene.addItem(p2)
    scene.addItem(p3)
    scene.addItem(p4)

    window = QGraphicsView(scene)
    window.setFrameStyle(0)
    window.setAlignment(Qt.AlignLeft | Qt.AlignTop)
    window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    machine = QStateMachine()
    machine.setGlobalRestorePolicy(QStateMachine.RestoreProperties)

    group = QState(machine)
    selectedRect = QRect(86, 86, 128, 128)

    idleState = QState(group)
    group.setInitialState(idleState)

    objects = [p1, p2, p3, p4]
    createStates(objects, selectedRect, group)
    createAnimations(objects, machine)

    machine.setInitialState(group)
    machine.start()

    window.resize(300, 300)
    window.show()
Ejemplo n.º 28
0
 def _make_save_state(self, form):
     s = QState()
     s.assignProperty(form.saveBtn, "enabled", True)
     return s
Ejemplo n.º 29
0
 def init_log_sm(self):
     self.log_state = QStateMachine()
     pre_system = QState()
     pre_event = QState()
     post_event = QState()
     self.log_state.addState(pre_system)
     self.log_state.addState(pre_event)
     self.log_state.addState(post_event)
     self.log_state.setInitialState(pre_system)
     pre_system.assignProperty(self.events, "enabled", False)
     pre_system.assignProperty(self.compass, "enabled", False)
     pre_system.assignProperty(self.exact_angle, "enabled", False)
     pre_event.assignProperty(self.events, "enabled", True)
     pre_event.assignProperty(self.compass, "enabled", False)
     pre_event.assignProperty(self.exact_angle, "enabled", False)
     post_event.assignProperty(self.compass, "enabled", True)
     post_event.assignProperty(self.exact_angle, "enabled", True)
     pre_system.addTransition(
         self.systems.acted, pre_event
     )
     pre_system.addTransition(self.timeout_timer.timeout, pre_system)
     pre_event.addTransition(self.timeout_timer.timeout, pre_system)
     post_event.addTransition(self.timeout_timer.timeout, pre_system)
     pre_event.addTransition(
         self.systems.acted, pre_event
     )
     post_event.addTransition(
         self.systems.acted, pre_event
     )
     post_event.addTransition(
         self.events.acted, post_event
     )
     pre_event.addTransition(
         self.events.acted, post_event
     )
     pre_system.entered.connect(self.events.switch_active)
     pre_system.entered.connect(self.systems.switch_active)
     pre_event.entered.connect(self.events.switch_active)
     post_event.exited.connect(self.compass.clear_state)
     post_event.exited.connect(lambda: self.exact_angle.log_angle(False))
     self.log_state.setRunning(True)
Ejemplo n.º 30
0
    scene.setBackgroundBrush(Qt.white)
    scene.addItem(p1)
    scene.addItem(p2)
    scene.addItem(p3)
    scene.addItem(p4)

    window = QGraphicsView(scene)
    window.setFrameStyle(0)
    window.setAlignment(Qt.AlignLeft | Qt.AlignTop)
    window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    machine = QStateMachine()
    machine.setGlobalRestorePolicy(QStateMachine.RestoreProperties)

    group = QState(machine)
    selectedRect = QRect(86, 86, 128, 128)

    idleState = QState(group)
    group.setInitialState(idleState)

    objects = [p1, p2, p3, p4]
    createStates(objects, selectedRect, group)
    createAnimations(objects, machine)

    machine.setInitialState(group)
    machine.start()

    window.resize(300, 300)
    window.show()
Ejemplo n.º 31
0
    def __init__(self, stickMan, keyReceiver):
        self.m_stickMan = stickMan
        self.m_keyReceiver = keyReceiver

        # Create animation group to be used for all transitions.
        self.m_animationGroup = QParallelAnimationGroup()
        stickManNodeCount = self.m_stickMan.nodeCount()
        self._pas = []
        for i in range(stickManNodeCount):
            pa = QPropertyAnimation(self.m_stickMan.node(i), 'pos')
            self._pas.append(pa)
            self.m_animationGroup.addAnimation(pa)

        # Set up intial state graph.
        self.m_machine = QStateMachine()
        self.m_machine.addDefaultAnimation(self.m_animationGroup)

        self.m_alive = QState(self.m_machine)
        self.m_alive.setObjectName('alive')

        # Make it blink when lightning strikes before entering dead animation.
        lightningBlink = QState(self.m_machine)
        lightningBlink.assignProperty(self.m_stickMan.scene(),
                                      'backgroundBrush', Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, 'penColor', Qt.black)
        lightningBlink.assignProperty(self.m_stickMan, 'fillColor', Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, 'isDead', True)

        timer = QTimer(lightningBlink)
        timer.setSingleShot(True)
        timer.setInterval(100)
        lightningBlink.entered.connect(timer.start)
        lightningBlink.exited.connect(timer.stop)

        self.m_dead = QState(self.m_machine)
        self.m_dead.assignProperty(self.m_stickMan.scene(), 'backgroundBrush',
                                   Qt.black)
        self.m_dead.assignProperty(self.m_stickMan, 'penColor', Qt.white)
        self.m_dead.assignProperty(self.m_stickMan, 'fillColor', Qt.black)
        self.m_dead.setObjectName('dead')

        # Idle state (sets no properties).
        self.m_idle = QState(self.m_alive)
        self.m_idle.setObjectName('idle')

        self.m_alive.setInitialState(self.m_idle)

        # Lightning strikes at random.
        self.m_alive.addTransition(LightningStrikesTransition(lightningBlink))
        lightningBlink.addTransition(timer.timeout, self.m_dead)

        self.m_machine.setInitialState(self.m_alive)
Ejemplo n.º 32
0
class StartTuto(QDialog):
    def __init__(self):
        super(StartTuto, self).__init__()
        QDialog.__init__(self)
        self.Next = 0
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setWindowTitle("لنتعلم معا")
        self.font = QFont('abdo salem')
        self.font.setPointSize(20)
        self.font.setBold(True)
        self.ex = QPushButton(self)
        self.ex.setFont(self.font)
        self.ex.setGeometry(400 + 80, 450, 150, 50)
        self.ex.setText('خروج')
        self.ex.setStyleSheet(
            "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n"
            "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n"
            "")
        self.ex.clicked.connect(self.Exit)
        self.hm = QPushButton(self)
        self.hm.setFont(self.font)
        self.hm.setGeometry(200 + 80, 450, 150, 50)
        self.hm.setText('الرئيسية')
        self.hm.setStyleSheet(
            "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n"
            "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n"
            "")
        self.hm.clicked.connect(self.home)
        self.resize(925, 500)
        self.Ind = [
            'data', 'if', 'for', 'while', 'def', 'class', 'oop', 'exp', 'prj2',
            'prj3', 'st'
        ]
        self.names = {
            'home': [
                'المتغير و\n أنواع البيانات', 'الجملة الشرطية\nIF',
                'حلقة التقسيم\nFOR', 'حلقة مادام\nWHILE', 'الدالة\nDEF',
                'الفئة\nClass', 'البرمجة كائنية\nالتوجه OOP', 'العبارات',
                'المشروع الاول\nRANGE', 'المشروع الثاني\nStr', 'ابدء'
            ],
            'data': [
                'المتغير', 'الأحرف ', 'الأرقام ', 'القائمة', 'القاموس',
                'الخطأ\nالصحيح', 'دوال \nانواع البيانات', 'الأمثلة'
            ],
            'if': [
                'الجملة الشرطية\nIF', 'ادوات المقارنة',
                'استعمالات\n ELIF و ELSE'
            ],
            'for': ['فكرة \nFOR', 'استعمالات \nFOR', 'امثلة'],
            'while': ['فكرة \nWHILE', 'استعمالات \nWHILE', 'امثلة'],
            'def': [
                'دالة بسيطة', 'arg\nدالة مع', '*arg\nدالة مع',
                'دالة مع\n**kwargs'
            ],
            'class': ['فئة بسيطة\n مع متغير', 'فئة بسيطة\n مع دالة'],
            'oop': ['البناء\n__init__', 'خاصية الاراثة', 'دالة\nsuper()'],
            'exp': ['عبارة\nreturn', 'عبارة\nassert', 'عبارة\nyield'],
            'prj2': ['المشروع'],
            'prj3': ['محاكات\nCount', 'محاكات\nFind', 'تطوير\nFind'],
            'st':
            'exit'
        }
        self.Home()

    def Home(self):
        self.items = []
        for i in range(len(self.names['home'])):
            item = QPushButton(self)
            item.setText(self.names['home'][i])
            item.setGeometry(395, 350, 120, 80)
            item.setStyleSheet(
                "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n"
                "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n"
                "")
            self.font.setPointSize(15)
            item.setFont(self.font)
            self.items.append(item)
            exec("""item.clicked.connect(partial(self.IND,i=%i))""" % (i))

        self.rootState = QState()
        self.tiledState = QState(self.rootState)
        self.centeredState = QState(self.rootState)
        for i, item in enumerate(self.items):
            self.tiledState.assignProperty(
                item, 'pos',
                QPointF(((i % 6) * 5.3) * 30, ((i // 6) * 5.3) * 30))

            self.centeredState.assignProperty(item, 'pos', QPointF())

        self.states = QStateMachine()
        self.states.addState(self.rootState)
        self.states.setInitialState(self.rootState)
        self.rootState.setInitialState(self.centeredState)
        self.group = QParallelAnimationGroup()
        for i, item in enumerate(self.items):
            anim = QPropertyAnimation(item, b'pos')
            anim.setStartValue(QPoint(400, 300))
            anim.setDuration(750 + i * 25)
            anim.setEasingCurve(QEasingCurve.InOutBack)
            self.group.addAnimation(anim)

        for u in self.items:
            trans = self.rootState.addTransition(u.clicked, self.tiledState)
            trans.addAnimation(self.group)
            self.states.start()

    def Exit(self):
        open('Files/choice', 'w').write('exit')
        self.close()

    def home(self):
        open('Files/choice', 'w').write('home')
        self.close()

    def IND(self, i):
        open('Files/choice', 'a').write(str(i))
        if self.Next != 2:
            self.Next += 1
            if self.names[self.Ind[i]] != 'exit':
                a = self.names[self.Ind[i]]
                k = 0
                for i in self.items[0:len(a)]:
                    i.setText(a[k])
                    k += 1
                for i in self.items[len(a):]:
                    i.hide()
            else:
                self.items[-1].hide()
        else:
            self.close()
Ejemplo n.º 33
0
    p5 = Pixmap(QPixmap(':/help-browser.png'))
    p6 = Pixmap(QPixmap(':/kchart.png'))

    scene = QGraphicsScene(0, 0, 400, 300)
    scene.setBackgroundBrush(scene.palette().window())
    scene.addItem(widget)
    scene.addItem(boxProxy)
    scene.addItem(p1)
    scene.addItem(p2)
    scene.addItem(p3)
    scene.addItem(p4)
    scene.addItem(p5)
    scene.addItem(p6)

    machine = QStateMachine()
    state1 = QState(machine)
    state2 = QState(machine)
    state3 = QState(machine)
    machine.setInitialState(state1)

    # State 1.
    state1.assignProperty(button, 'text', "Switch to state 2")
    state1.assignProperty(widget, 'geometry', QRectF(0, 0, 400, 150))
    state1.assignProperty(box, 'geometry', QRect(-200, 150, 200, 150))
    state1.assignProperty(p1, 'pos', QPointF(68, 185))
    state1.assignProperty(p2, 'pos', QPointF(168, 185))
    state1.assignProperty(p3, 'pos', QPointF(268, 185))
    state1.assignProperty(p4, 'pos', QPointF(68 - 150, 48 - 150))
    state1.assignProperty(p5, 'pos', QPointF(168, 48 - 150))
    state1.assignProperty(p6, 'pos', QPointF(268 + 150, 48 - 150))
    state1.assignProperty(p1, 'rotation', 0.0)
Ejemplo n.º 34
0
    def createState(self):
        # state defintion
        mainState = QState(self.fsm)
        finalState = QFinalState(self.fsm)
        self.fsm.setInitialState(mainState)
        
        initState = QState(mainState)
        openState = QState(mainState)
        mainState.setInitialState(initState)

        standbyState = QState(openState)
        processingState = QState(openState)
        openState.setInitialState(standbyState)

        # transition defition
        initState.addTransition(self.sigComPortOpened, openState) 
        openState.addTransition(self.sigComPortClosed, initState)

        standbyState.addTransition(self.sigPowerOn, processingState)
        processingState.addTransition(self.sigPowerOff, standbyState)

        initState.entered.connect(self.initStateEntered)
        openState.entered.connect(self.openStateEntered)
        standbyState.entered.connect(self.standbyStateEntered)
        processingState.entered.connect(self.processingStateEntered)

        # fsm start
        self.fsm.start()
        pass
Ejemplo n.º 35
0
def twoStateButton(name,stateMachine,action,*states):
    st = QStateMachine()

    a1,a2 = states
    s1,s2 = QState(),QState()
    icon1 = QIcon(Icons + a1[1])
    icon2 = QIcon(Icons + a2[1])
    s1.setObjectName(a1[0])
    s2.setObjectName(a2[0])
    s1.assignProperty(action, "icon", icon1)
    s2.assignProperty(action, "icon", icon2)
    s1.assignProperty(action, "text", a1[0])
    s2.assignProperty(action, "text", a2[0])

    s1.addTransition(action.triggered, s2)
    s2.addTransition(action.triggered, s1)
    st.addState(s1)
    st.addState(s2)
    st.setInitialState(s1)

    stateMachine[name] = st
    st.start()
Ejemplo n.º 36
0
def createStates(objects, selectedRect, parent):
    for obj in objects:
        state = QState(parent)
        state.assignProperty(obj, 'geometry', selectedRect)
        parent.addTransition(obj.clicked, state)
Ejemplo n.º 37
0
    def loadState(self, dev, stateParam, stateID = ""):

        curExecContext = ScExecContext()
        curExecContext.stateMachine = self.stateMachine
        curHistoryState = None
        debug = True

        r = QXmlStreamReader(dev)

        while not r.atEnd():
            r.readNext()
            if r.isStartElement():
                logger.info("Element :<%s>", r.name())
                #
                # <scxml>
                #
                name = r.name().lower()
                if name == "scxml":

                    if stateID == "":
                        topLevelState = curState = stateParam
                        self.stateInfo[curState] = r.attributes().value("initial")
                        if curState == self.stateMachine:
                            pass
                #
                # <state> || <parallel>
                #
                elif name == "state" or name == "parallel":
                    inRoot = False
                    stateId = r.attributes().value("id")
                    newState = None
                    #
                    # Create state
                    #
                    if curState is not None:
                        logger.info("Creating state [%s] child of [%s]", stateId, curState.objectName())
                        type = QState.ExclusiveStates if name == "state" else QState.ParallelStates
                        newState = QState(type, curState)
                    #
                    # ???
                    #
                    elif stateId == stateID:
                        topLevelState = newState = stateParam

                    if newState is not None:
                        self.stateInfo[newState] = r.attributes().value("initial")
                        newState.setObjectName(stateId)
                        #
                        # initial state
                        #
                        if stateId is not "" and self.stateInfo[curState] == stateId:
                            if curState == self.stateMachine:
                                logger.info("Setting [%s] initial state to [%s]",
                                            self.stateMachine.objectName(),
                                            newState.objectName())
                                self.stateMachine.setInitialState(newState)
                            else:
                                logger.info("Setting [%s] initial state to [%s]",
                                            curState.objectName(),
                                            newState.objectName())
                                curState.setInitialState(newState)
                        #
                        # TODO implement src attribute management in state element
                        #
                        initialID = r.attributes().value("initial")
                        self.stateByID[stateId] = newState
                        curState = newState
                        curExecContext.state = newState

                        if debug:

                            # Add entry and exit log

                            curExecContext.script = 'logger.debug("[scxml] [debug] > Entering state: [' + stateId + ']")'
                            curExecContext.type = ScExecContext.StateEntry
                            curExecContext.applyScript()
                            curExecContext.script = 'logger.debug("[scxml] [debug] < Exiting state: [' + stateId + ']")'
                            curExecContext.type = ScExecContext.StateExit
                            curExecContext.applyScript()
                #
                # <initial>
                #
                elif name == "initial":
                    if curState is not None and self.stateInfo[curState] == "":
                        logger.info("Creating state [%s] child of [%s]", stateId, curState.objectName())
                        newState = QState(curState)
                        curState.setInitialState(newState)
                #
                # <history>
                #
                elif name == "history":
                    if curState is not None:
                        stateId = r.attributes().value("id")
                        type = r.attributes().value("type")
                        type = QHistoryState.ShallowHistory if type == "shallow" else QHistoryState.DeepHistory
                        curHistoryState = QHistoryState(type)
                        curHistoryState.setObjectName(stateId)
                        self.stateByID[stateId] = curHistoryState
                #
                # <final>
                #
                elif name == "final":
                    if curState is not None:
                        stateId = r.attributes().value("id")
                        f = QFinalState(curState)
                        f.setObjectName(stateId)
                        curExecContext.state = f
                        self.statesWithFinal.add(curState)
                        gp = curState.parentState()
                        if gp is not None:
                            if gp.childMode() == QState.ParallelStates:
                                self.statesWithFinal.add()
                        self.stateByID[stateId] = f

                        if debug:

                            # Add entry and exit log

                            curExecContext.script = 'logger.debug("[scxml] [debug] > Entering final state: [' + stateId + ']")'
                            curExecContext.type = ScExecContext.StateEntry
                            curExecContext.applyScript()
                            curExecContext.script = 'logger.debug("[scxml] [debug] < Exiting final state: [' + stateId + ']")'
                            curExecContext.type = ScExecContext.StateExit
                            curExecContext.applyScript()

                #
                # <script>
                #
                elif name == "script":
                    txt = r.readElementText()
                    #
                    # The SCXML Processor MUST evaluate any <script> element that is a child
                    # of <scxml> at document load time
                    #
                    if curExecContext.type == ScExecContext.Unknown and curState == topLevelState:
                        # TODO execute script
                        pass
                    else:
                        curExecContext.script += txt
                #
                # <log>
                #
                elif name == "log":
                    curExecContext.script += 'logger.' + r.attributes().value("level") + '("[' + \
                                             r.attributes().value("label") + '] [' +  \
                                             r.attributes().value("level") + '] ' + r.attributes().value("expr") + '")'
                #
                # <assign>
                #
                elif name == "assign":
                    pass
                #
                # <if>
                #
                elif name == "if":
                    pass
                #
                # <elseif>
                #
                elif name == "elseif":
                    pass
                #
                # <else>
                #
                elif name == "else":
                    pass
                #
                # <cancel>
                #
                elif name == "cancel":
                    pass
                #
                # <onentry>
                #
                elif name == "onentry":
                    curExecContext.type = ScExecContext.StateEntry
                    curExecContext.script = ""
                #
                # <onexit>
                #
                elif name == "onexit":
                    curExecContext.type = ScExecContext.StateExit
                    curExecContext.script = ""
                #
                # <raise>
                #
                elif name == "raise":
                    pass
                #
                # <send>
                #
                elif name == "send":
                    pass
                #
                # <invoke>
                #
                elif name == "invoke":
                    pass
                #
                # <transition>
                #
                elif name == "transition":
                    if curHistoryState is not None:
                        inf = ScHistoryInfo()
                        inf.hstate = curHistoryState
                        inf.defaultStateID = r.attributes().value("target")
                        self.historyInfo.append(inf)
                    else:
                        inf = ScTransitionInfo()
                        inf.targets = r.attributes().value("target").split() # TODO split targets
                        curExecContext.type = ScExecContext.Transition

                        curExecContext.script = ""
                        if debug:
                            curExecContext.script = 'logger.debug("[scxml] [debug] = Transitioning to: [' \
                                                    + ', '.join(inf.targets) + ']")' + '\n'


                        curTransitions = list()
                        inf.transitions = list()
                        self.transitionsInf.append(inf)

                        for pfx in r.attributes().value("event").split(' '):
                            sigTransition = None
                            if pfx == '':

                                # For eventless transition create QScxmlEventlessTransition transition

                                sigTransition = QScxmlEventlessTransition(self.stateMachine)

                            elif pfx.startswith("q-signal:"):

                                # For all q-signal event, add a QSxcmlSignalTransition

                                self.signalEvents.append(pfx)

                                # get object name (a.b.c) => a

                                objName = pfx[pfx.index(':')+1:pfx.index('.')]

                                # get object reference

                                obj = self.stateMachine.registeredObjects[objName]

                                # get signal reference

                                for attr in pfx[pfx.index('.')+1:].split('.'):
                                    sig = getattr(obj, attr)
                                    obj = sig

                                # create Signal transition

                                sigTransition = QScxmlSignalTransition(sig, self.stateMachine)

                            if sigTransition is not None:

                                # add condition to transition

                                sigTransition.setConditionExpression(r.attributes().value("cond"))

                                # add transition to current state

                                curState.addTransition(sigTransition)

                                # append sigTransition to transition info

                                inf.transitions.append(sigTransition)

                                # append sigTransition to curTransitions list

                                curTransitions.append(sigTransition)

                            else:
                                logger.error("Transition creation error")
            #
            # End element
            #
            elif r.isEndElement():
                name = r.name().lower()
                #
                # </state> or </parallel>
                #
                if name == "state" or name == "parallel":
                    if curState == topLevelState:
                        return
                    else:
                        curState = curState.parent()
                        curExecContext.state = curState
                #
                # </history>
                #
                elif name == "history":
                    curHistoryState = None
                #
                # </final>
                #
                elif name == "final":
                    curExecContext.state = curExecContext.state.parentState()
                #
                # </if>
                #
                elif name == "if":
                    pass
                #
                # </send> </raise>
                #
                elif name == "send" or name == "raise":
                    pass
                #
                # </onentry> </onexit> </scxml>
                #
                elif name == "onentry" or name == "onexit" or name == "scxml":
                    curExecContext.state = curState
                    curExecContext.type = ScExecContext.StateExit if name == "onexit" else ScExecContext.StateEntry
                    curExecContext.applyScript()
                    curExecContext.type = ScExecContext.Unknown
                    curExecContext.script = ""
                #
                # </transition>
                #
                elif name == "transition":
                    if curHistoryState is None:
                        curExecContext.transitions = curTransitions
                        curExecContext.type = ScExecContext.Transition
                        curExecContext.applyScript()
                        curExecContext.script = ""
                    curExecContext.type = ScExecContext.Unknown
Ejemplo n.º 38
0
class LifeCycle(object):
    def __init__(self, stickMan, keyReceiver):
        self.m_stickMan = stickMan
        self.m_keyReceiver = keyReceiver

        # Create animation group to be used for all transitions.
        self.m_animationGroup = QParallelAnimationGroup()
        stickManNodeCount = self.m_stickMan.nodeCount()
        self._pas = []
        for i in range(stickManNodeCount):
            pa = QPropertyAnimation(self.m_stickMan.node(i), 'pos')
            self._pas.append(pa)
            self.m_animationGroup.addAnimation(pa)

        # Set up intial state graph.
        self.m_machine = QStateMachine()
        self.m_machine.addDefaultAnimation(self.m_animationGroup)

        self.m_alive = QState(self.m_machine)
        self.m_alive.setObjectName('alive')

        # Make it blink when lightning strikes before entering dead animation.
        lightningBlink = QState(self.m_machine)
        lightningBlink.assignProperty(self.m_stickMan.scene(),
                                      'backgroundBrush', Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, 'penColor', Qt.black)
        lightningBlink.assignProperty(self.m_stickMan, 'fillColor', Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, 'isDead', True)

        timer = QTimer(lightningBlink)
        timer.setSingleShot(True)
        timer.setInterval(100)
        lightningBlink.entered.connect(timer.start)
        lightningBlink.exited.connect(timer.stop)

        self.m_dead = QState(self.m_machine)
        self.m_dead.assignProperty(self.m_stickMan.scene(), 'backgroundBrush',
                                   Qt.black)
        self.m_dead.assignProperty(self.m_stickMan, 'penColor', Qt.white)
        self.m_dead.assignProperty(self.m_stickMan, 'fillColor', Qt.black)
        self.m_dead.setObjectName('dead')

        # Idle state (sets no properties).
        self.m_idle = QState(self.m_alive)
        self.m_idle.setObjectName('idle')

        self.m_alive.setInitialState(self.m_idle)

        # Lightning strikes at random.
        self.m_alive.addTransition(LightningStrikesTransition(lightningBlink))
        lightningBlink.addTransition(timer.timeout, self.m_dead)

        self.m_machine.setInitialState(self.m_alive)

    def setDeathAnimation(self, fileName):
        deathAnimation = self.makeState(self.m_dead, fileName)
        self.m_dead.setInitialState(deathAnimation)

    def start(self):
        self.m_machine.start()

    def addActivity(self, fileName, key):
        state = self.makeState(self.m_alive, fileName)
        self.m_alive.addTransition(
            KeyPressTransition(self.m_keyReceiver, key, state))

    def makeState(self, parentState, animationFileName):
        topLevel = QState(parentState)

        animation = Animation()

        file = QFile(animationFileName)
        if file.open(QIODevice.ReadOnly):
            animation.load(file)

        frameCount = animation.totalFrames()
        previousState = None
        for i in range(frameCount):
            animation.setCurrentFrame(i)

            frameState = QState(topLevel)
            nodeCount = animation.nodeCount()
            for j in range(nodeCount):
                frameState.assignProperty(self.m_stickMan.node(j), 'pos',
                                          animation.nodePos(j))

            frameState.setObjectName('frame %d' % i)

            if previousState is None:
                topLevel.setInitialState(frameState)
            else:
                previousState.addTransition(previousState.propertiesAssigned,
                                            frameState)

            previousState = frameState

        previousState.addTransition(previousState.propertiesAssigned,
                                    topLevel.initialState())

        return topLevel
Ejemplo n.º 39
0
    scene = QGraphicsScene(0, 0, 300, 300)
    scene.setBackgroundBrush(Qt.black)
    scene.addItem(button1)
    scene.addItem(button2)
    scene.addItem(button3)
    scene.addItem(button4)

    window = QGraphicsView(scene)
    window.setFrameStyle(0)
    window.setAlignment(Qt.AlignLeft | Qt.AlignTop)
    window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    machine = QStateMachine()

    group = QState()
    timer = QTimer()
    timer.setInterval(1250)
    timer.setSingleShot(True)
    group.entered.connect(timer.start)

    state1 = createGeometryState(button1, QRect(100, 0, 50, 50), button2,
                                 QRect(150, 0, 50, 50), button3,
                                 QRect(200, 0, 50, 50), button4,
                                 QRect(250, 0, 50, 50), group)

    state2 = createGeometryState(button1, QRect(250, 100, 50, 50), button2,
                                 QRect(250, 150, 50, 50), button3,
                                 QRect(250, 200, 50, 50), button4,
                                 QRect(250, 250, 50, 50), group)
Ejemplo n.º 40
0
    def makeState(self, parentState, animationFileName):
        topLevel = QState(parentState)

        animation = Animation()

        file = QFile(animationFileName)
        if file.open(QIODevice.ReadOnly):
            animation.load(file)

        frameCount = animation.totalFrames()
        previousState = None
        for i in range(frameCount):
            animation.setCurrentFrame(i)

            frameState = QState(topLevel)
            nodeCount = animation.nodeCount()
            for j in range(nodeCount):
                frameState.assignProperty(self.m_stickMan.node(j), 'pos',
                                          animation.nodePos(j))

            frameState.setObjectName('frame %d' % i)

            if previousState is None:
                topLevel.setInitialState(frameState)
            else:
                previousState.addTransition(previousState.propertiesAssigned,
                                            frameState)

            previousState = frameState

        previousState.addTransition(previousState.propertiesAssigned,
                                    topLevel.initialState())

        return topLevel
Ejemplo n.º 41
0
    def __init__(self, scene, x_max, y_max, back_color):

        scene = QGraphicsScene(0, 0, x_max, y_max)
        scene.setBackgroundBrush(back_color)

        color = [Qt.green, Qt.lightGray, Qt.darkYellow, QtGui.QColor.fromRgb(255, 85, 0)]
        self.anim_butt = [ QGraphicsRectWidget(color[j]) for j in range(4) ]
        for j in range(4):
            scene.addItem(self.anim_butt[j])

        self.window = QGraphicsView(scene)
        self.window.setFrameStyle(0)
        self.window.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.machine = QStateMachine()

        self.group = QState()
        self.timer = QTimer()
        self.timer.setInterval(1250)
        self.timer.setSingleShot(True)
        self.group.entered.connect(self.timer.start)

        # set states positions
        anim_state_rects = [ [QRect(x_max*xp/6, y_max*yp/4, 8, 8) for xp in range(4)] for yp in range(4) ]
        self.states = [ self.createGeometryState(
                                self.anim_butt[0], anim_state_rects[0][j], self.anim_butt[1], anim_state_rects[1][j],
                                self.anim_butt[2], anim_state_rects[2][j], self.anim_butt[3], anim_state_rects[3][j],
                                self.group
                            ) for j in range(4) ]

        self.group.setInitialState(self.states[0])


        self.animationGroup = QParallelAnimationGroup()
        self.anim = QPropertyAnimation(self.anim_butt[3], 'geometry')
        self.anim.setDuration(1250)
        self.anim.setEasingCurve(QEasingCurve.InBack)
        self.animationGroup.addAnimation(self.anim)

        self.subGroup = QSequentialAnimationGroup(self.animationGroup)
        self.subGroup.addPause(100)
        self.anim = QPropertyAnimation(self.anim_butt[2], 'geometry')
        self.anim.setDuration(1000)
        self.anim.setEasingCurve(QEasingCurve.OutElastic)
        self.subGroup.addAnimation(self.anim)

        self.subGroup = QSequentialAnimationGroup(self.animationGroup)
        self.subGroup.addPause(500)
        self.anim = QPropertyAnimation(self.anim_butt[1], 'geometry')
        self.anim.setDuration(500)
        self.anim.setEasingCurve(QEasingCurve.OutElastic)
        self.subGroup.addAnimation(self.anim)

        self.subGroup = QSequentialAnimationGroup(self.animationGroup)
        self.subGroup.addPause(750)
        self.anim = QPropertyAnimation(self.anim_butt[0], 'geometry')
        self.anim.setDuration(250)
        self.anim.setEasingCurve(QEasingCurve.OutElastic)
        self.subGroup.addAnimation(self.anim)

        self.stateSwitcher = StateSwitcher(self.machine)
        self.group.addTransition(self.timer.timeout, self.stateSwitcher)
        for j in range(4):
            self.stateSwitcher.addState(self.states[j], self.animationGroup)

        self.machine.addState(self.group)
        self.machine.setInitialState(self.group)
        self.machine.start()
Ejemplo n.º 42
0
def createStates(objects, selectedRect, parent):
    for obj in objects:
        state = QState(parent)
        state.assignProperty(obj, 'geometry', selectedRect)
        parent.addTransition(obj.clicked, state)
Ejemplo n.º 43
0
class LifeCycle(object):
    def __init__(self, stickMan, keyReceiver):
        self.m_stickMan = stickMan
        self.m_keyReceiver = keyReceiver

        # Create animation group to be used for all transitions.
        self.m_animationGroup = QParallelAnimationGroup()
        stickManNodeCount = self.m_stickMan.nodeCount()
        self._pas = []
        for i in range(stickManNodeCount):
            pa = QPropertyAnimation(self.m_stickMan.node(i), b"pos")
            self._pas.append(pa)
            self.m_animationGroup.addAnimation(pa)

        # Set up intial state graph.
        self.m_machine = QStateMachine()
        self.m_machine.addDefaultAnimation(self.m_animationGroup)

        self.m_alive = QState(self.m_machine)
        self.m_alive.setObjectName("alive")

        # Make it blink when lightning strikes before entering dead animation.
        lightningBlink = QState(self.m_machine)
        lightningBlink.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, "penColor", Qt.black)
        lightningBlink.assignProperty(self.m_stickMan, "fillColor", Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, "isDead", True)

        timer = QTimer(lightningBlink)
        timer.setSingleShot(True)
        timer.setInterval(100)
        lightningBlink.entered.connect(timer.start)
        lightningBlink.exited.connect(timer.stop)

        self.m_dead = QState(self.m_machine)
        self.m_dead.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.black)
        self.m_dead.assignProperty(self.m_stickMan, "penColor", Qt.white)
        self.m_dead.assignProperty(self.m_stickMan, "fillColor", Qt.black)
        self.m_dead.setObjectName("dead")

        # Idle state (sets no properties).
        self.m_idle = QState(self.m_alive)
        self.m_idle.setObjectName("idle")

        self.m_alive.setInitialState(self.m_idle)

        # Lightning strikes at random.
        self.m_alive.addTransition(LightningStrikesTransition(lightningBlink))
        lightningBlink.addTransition(timer.timeout, self.m_dead)

        self.m_machine.setInitialState(self.m_alive)

    def setDeathAnimation(self, fileName):
        deathAnimation = self.makeState(self.m_dead, fileName)
        self.m_dead.setInitialState(deathAnimation)

    def start(self):
        self.m_machine.start()

    def addActivity(self, fileName, key):
        state = self.makeState(self.m_alive, fileName)
        self.m_alive.addTransition(KeyPressTransition(self.m_keyReceiver, key, state))

    def makeState(self, parentState, animationFileName):
        topLevel = QState(parentState)

        animation = Animation()

        file = QFile(animationFileName)
        if file.open(QIODevice.ReadOnly):
            animation.load(file)

        frameCount = animation.totalFrames()
        previousState = None
        for i in range(frameCount):
            animation.setCurrentFrame(i)

            frameState = QState(topLevel)
            nodeCount = animation.nodeCount()
            for j in range(nodeCount):
                frameState.assignProperty(self.m_stickMan.node(j), "pos", animation.nodePos(j))

            frameState.setObjectName("frame %d" % i)

            if previousState is None:
                topLevel.setInitialState(frameState)
            else:
                previousState.addTransition(previousState.propertiesAssigned, frameState)

            previousState = frameState

        previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState())

        return topLevel
Ejemplo n.º 44
0
    def init_ui(self):
        vbox = QVBoxLayout()

        button1 = QPushButton('fuck1')

        vbox.addWidget(button1)

        button1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        vbox.setContentsMargins(80, 80, 80, 80)

        self.setLayout(vbox)

        machine = QStateMachine(self)
        s1 = QState()
        s1.assignProperty(button1, "text", "Outside")
        s2 = QState()
        s2.assignProperty(button1, "text", "Inside")

        enter_transition = QEventTransition(button1, QEvent.Enter)
        enter_transition.setTargetState(s2)
        s1.addTransition(enter_transition)

        leave_transition = QEventTransition(button1, QEvent.Leave)
        leave_transition.setTargetState(s1)
        s2.addTransition(leave_transition)

        s3 = QState()
        s3.assignProperty(button1, 'text', 'Pressing...')

        press_transition = QEventTransition(button1, QEvent.MouseButtonPress)
        press_transition.setTargetState(s3)
        s2.addTransition(press_transition)

        release_transition = QEventTransition(button1,
                                              QEvent.MouseButtonRelease)
        release_transition.setTargetState(s2)
        s3.addTransition(release_transition)

        machine.addState(s1)
        machine.addState(s2)
        machine.addState(s3)

        machine.setInitialState(s1)
        machine.start()
Ejemplo n.º 45
0
    def __init__(self, stickMan, keyReceiver):
        self.m_stickMan = stickMan
        self.m_keyReceiver = keyReceiver

        # Create animation group to be used for all transitions.
        self.m_animationGroup = QParallelAnimationGroup()
        stickManNodeCount = self.m_stickMan.nodeCount()
        self._pas = []
        for i in range(stickManNodeCount):
            pa = QPropertyAnimation(self.m_stickMan.node(i), b"pos")
            self._pas.append(pa)
            self.m_animationGroup.addAnimation(pa)

        # Set up intial state graph.
        self.m_machine = QStateMachine()
        self.m_machine.addDefaultAnimation(self.m_animationGroup)

        self.m_alive = QState(self.m_machine)
        self.m_alive.setObjectName("alive")

        # Make it blink when lightning strikes before entering dead animation.
        lightningBlink = QState(self.m_machine)
        lightningBlink.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, "penColor", Qt.black)
        lightningBlink.assignProperty(self.m_stickMan, "fillColor", Qt.white)
        lightningBlink.assignProperty(self.m_stickMan, "isDead", True)

        timer = QTimer(lightningBlink)
        timer.setSingleShot(True)
        timer.setInterval(100)
        lightningBlink.entered.connect(timer.start)
        lightningBlink.exited.connect(timer.stop)

        self.m_dead = QState(self.m_machine)
        self.m_dead.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.black)
        self.m_dead.assignProperty(self.m_stickMan, "penColor", Qt.white)
        self.m_dead.assignProperty(self.m_stickMan, "fillColor", Qt.black)
        self.m_dead.setObjectName("dead")

        # Idle state (sets no properties).
        self.m_idle = QState(self.m_alive)
        self.m_idle.setObjectName("idle")

        self.m_alive.setInitialState(self.m_idle)

        # Lightning strikes at random.
        self.m_alive.addTransition(LightningStrikesTransition(lightningBlink))
        lightningBlink.addTransition(timer.timeout, self.m_dead)

        self.m_machine.setInitialState(self.m_alive)