Example #1
0
def fin(pix):  ## delete pixitem
    node = Node(pix)
    node.pix.setOriginPt()
    sync = random.randint(6, 10) * 75
    rot = 270
    if not random.randint(0, 1): rot = -270

    rotate = QPropertyAnimation(node, b'rotate')
    rotate.setDuration(sync)
    rotate.setStartValue(node.pix.rotation)
    rotate.setEndValue(rot + node.pix.rotation)

    opacity = QPropertyAnimation(node, b'opacity')
    opacity.setDuration(sync)
    opacity.setStartValue(node.pix.opacity())
    opacity.setEndValue(0)

    scale = QPropertyAnimation(node, b'scale')
    scale.setDuration(sync)
    scale.setStartValue(node.pix.scale)
    scale.setEndValue(node.pix.scale * .25)

    group = QParallelAnimationGroup()

    group.addAnimation(rotate)
    group.addAnimation(opacity)
    group.addAnimation(scale)

    group.setLoopCount(1)

    return group
Example #2
0
    def setupUi(self, popup_post):
        super().setupUi(popup_post)
        self.setAttribute(Qt.WA_TranslucentBackground)

        desktop = QApplication.desktop()
        self.move(desktop.width() - 50 - self.width(),
                  desktop.height() - 300 - self.height())

        # 因为带浏览器的透明窗口不能渲染,浏览器放在独立窗口
        self.content_view = WeiboWebView(self)
        self.content_view.setWindowOpacity(0)

        # 淡出淡入动画
        self._window_fade_anim = QPropertyAnimation(self, b'windowOpacity',
                                                    self)
        self._window_fade_anim.setDuration(300)
        self._window_fade_anim.setStartValue(0)
        self._window_fade_anim.setEndValue(0.5)
        self._content_fade_anim = QPropertyAnimation(self.content_view,
                                                     b'windowOpacity', self)
        self._content_fade_anim.setDuration(300)
        self._content_fade_anim.setStartValue(0)
        self._content_fade_anim.setEndValue(0.7)
        self._fade_anim_group = QParallelAnimationGroup(self)
        self._fade_anim_group.addAnimation(self._window_fade_anim)
        self._fade_anim_group.addAnimation(self._content_fade_anim)
        self._fade_anim_group.finished.connect(self._on_anim_finish)
Example #3
0
 def __init__(self, playlist: list = None, parent=None):
     super().__init__(parent)
     self.playlist = playlist.copy()
     self.currentIndex = 0
     self.isPlaylistVisible = False
     # 创建小部件
     self.blurPixmap = None
     self.blurBackgroundPic = QLabel(self)
     self.blurCoverThread = BlurCoverThread(self)
     self.songInfoCardChute = SongInfoCardChute(self, self.playlist)
     self.parallelAniGroup = QParallelAnimationGroup(self)
     self.songInfoCardChuteAni = QPropertyAnimation(self.songInfoCardChute,
                                                    b'geometry')
     self.playBar = PlayBar(self)
     self.songListWidget = SongListWidget(self.playlist, self)
     self.smallestModeInterface = SmallestPlayModeInterface(playlist, self)
     self.playBarAni = QPropertyAnimation(self.playBar, b'geometry')
     self.songListWidgetAni = QPropertyAnimation(self.songListWidget,
                                                 b'geometry')
     self.guideLabel = QLabel('在这里,你将看到正在播放的歌曲以及即将播放的歌曲。', self)
     self.randomPlayAllButton = ThreeStateButton(
         {
             'normal':
             r'resource\images\playing_interface\全部随机播放_normal_256_39.png',
             'hover':
             r'resource\images\playing_interface\全部随机播放_hover_256_39.png',
             'pressed':
             r'resource\images\playing_interface\全部随机播放_pressed_256_39.png'
         }, self, (256, 39))
     # 创建定时器
     self.showPlaylistTimer = QTimer(self)
     self.hidePlaylistTimer = QTimer(self)
     # 初始化
     self.__initWidget()
Example #4
0
    def __init__(self, title="", parent=None):
        super(CollapsibleBox, self).__init__(parent)

        self.toggle_button = QToolButton(text=title,
                                         checkable=True,
                                         checked=False)
        self.toggle_button.setStyleSheet("QToolButton { border: none; }")
        self.toggle_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toggle_button.setArrowType(Qt.RightArrow)
        self.toggle_button.pressed.connect(self.on_pressed)

        self.toggle_animation = QParallelAnimationGroup(self)

        self.content_area = QScrollArea(maximumHeight=0, minimumHeight=0)
        self.content_area.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Fixed)
        self.content_area.setFrameShape(QFrame.NoFrame)

        lay = QVBoxLayout(self)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.toggle_button)
        lay.addWidget(self.content_area)

        self.toggle_animation.addAnimation(
            QPropertyAnimation(self, b"minimumHeight"))
        self.toggle_animation.addAnimation(
            QPropertyAnimation(self, b"maximumHeight"))
        self.toggle_animation.addAnimation(
            QPropertyAnimation(self.content_area, b"maximumHeight"))
Example #5
0
 def __init__(self, playlist: list = None, parent=None):
     super().__init__(parent)
     self.playlist = playlist.copy()
     self.currentIndex = 0
     self.isPlaylistVisible = False
     # 创建小部件
     self.blurPixmap = None
     self.blurBackgroundPic = QLabel(self)
     self.blurCoverThread = BlurCoverThread(self)
     self.songInfoCardChute = SongInfoCardChute(self, self.playlist)
     self.parallelAniGroup = QParallelAnimationGroup(self)
     self.songInfoCardChuteAni = QPropertyAnimation(self.songInfoCardChute,
                                                    b"geometry")
     self.playBar = PlayBar(self)
     self.songListWidget = SongListWidget(self.playlist, self)
     self.smallestModeInterface = SmallestPlayModeInterface(playlist, self)
     self.playBarAni = QPropertyAnimation(self.playBar, b"geometry")
     self.songListWidgetAni = QPropertyAnimation(self.songListWidget,
                                                 b"geometry")
     self.guideLabel = QLabel("在这里,你将看到正在播放的歌曲以及即将播放的歌曲。", self)
     self.randomPlayAllButton = ThreeStatePushButton(
         {
             "normal":
             r"app\resource\images\playing_interface\全部随机播放_normal.png",
             "hover":
             r"app\resource\images\playing_interface\全部随机播放_hover.png",
             "pressed":
             r"app\resource\images\playing_interface\全部随机播放_pressed.png",
         }, " 随机播放你收藏中的所有内容", (30, 22), self)
     # 创建定时器
     self.showPlaylistTimer = QTimer(self)
     self.hidePlaylistTimer = QTimer(self)
     # 初始化
     self.__initWidget()
Example #6
0
    def __init__(self,
                 orientation=Orientation.HORIZONTAL,
                 animationDuration=120,
                 parent=None):
        QWidget.__init__(self, parent)

        self.opened = False
        self.orientation = orientation
        self.animationDuration = animationDuration
        self.mainLayout = None
        self.animator = QParallelAnimationGroup()

        if orientation is self.Orientation.HORIZONTAL:
            self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

            self.setMaximumWidth(0)
            self.setMinimumWidth(0)
            # let the entire widget grow and shrink with its content
            self.animator.addAnimation(QPropertyAnimation(self))
            self.animator.addAnimation(
                QPropertyAnimation(self, b"minimumWidth"))
            self.animator.addAnimation(
                QPropertyAnimation(self, b"maximumWidth"))

        elif orientation is self.Orientation.VERTICAL:
            self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

            self.setMaximumHeight(0)
            self.setMinimumHeight(0)
            # let the entire widget grow and shrink with its content
            self.animator.addAnimation(QPropertyAnimation(self))
            self.animator.addAnimation(
                QPropertyAnimation(self, b"minimumHeight"))
            self.animator.addAnimation(
                QPropertyAnimation(self, b"maximumHeight"))
Example #7
0
 def __init__(self, playlist: list, parent=None):
     super().__init__(parent)
     self.playlist = playlist
     self.currentIndex = 0
     self.shiftLeftTime = 0
     self.shiftRightTime = 0
     self.songInfoCard_list = []
     self.__unCompleteShift_list = []
     # 创建按钮
     self.playButton = PlayButton(
         [
             r"app\resource\images\smallest_play_mode\播放_45_45.png",
             r"app\resource\images\smallest_play_mode\暂停_45_45.png",
         ],
         self,
     )
     self.lastSongButton = SmallestPlayModeButton(
         r"app\resource\images\smallest_play_mode\上一首_45_45.png", self)
     self.nextSongButton = SmallestPlayModeButton(
         r"app\resource\images\smallest_play_mode\下一首_45_45.png", self)
     self.exitSmallestModeButton = BasicCircleButton(
         r"app\resource\images\playing_interface\最小模式播放_47_47.png", self)
     self.progressBar = QSlider(Qt.Horizontal, self)
     self.aniGroup = QParallelAnimationGroup(self)
     # 创建歌曲信息卡
     self.__createSongInfoCards()
     # 初始化
     self.__initWidget()
Example #8
0
 def addWidget(self,
               widget,
               deltaX: int = 0,
               deltaY: int = 22,
               isNeedOpacityAni=True):
     """ 添加堆叠窗口\n
     Parameters
     -----------
     widget : 窗口\n
     deltaX : 窗口动画开始到结束的x轴偏移量\n
     deltaY : 窗口动画开始到结束的y轴偏移量\n
     isNeedOpacityAni : 是否需要淡入淡出动画\n
     """
     super().addWidget(widget)
     # 创建动画
     popUpAni = QPropertyAnimation(widget, b'geometry')
     aniGroup = QParallelAnimationGroup(self)
     aniGroup.addAnimation(popUpAni)
     self.__widgetAni_list.append({
         'widget': widget,
         'deltaX': deltaX,
         'deltaY': deltaY,
         'aniGroup': aniGroup,
         'popUpAni': popUpAni,
         'isNeedOpacityAni': isNeedOpacityAni
     })
Example #9
0
 def __createAlbumCards(self):
     """ 将专辑卡添加到窗口中 """
     # 创建并行动画组
     self.hideCheckBoxAniGroup = QParallelAnimationGroup(self)
     self.hideCheckBoxAni_list = []
     for albumInfo in self.albumInfo_list:
         self.__createOneAlbumCard(albumInfo)
Example #10
0
def reprise(pix):  ## reposition pixitems to starting x,y, etc.
    node = Node(pix)
    node.pix.setOriginPt()
    sync = 1000

    reprise = QPropertyAnimation(node, b'pos')
    reprise.setDuration(sync)
    reprise.setStartValue(node.pix.pos())
    reprise.setEndValue(QPointF(pix.x, pix.y))

    spin = QPropertyAnimation(node, b'rotate')
    spin.setDuration(sync)
    spin.setStartValue(node.pix.rotation)
    spin.setKeyValueAt(0.50, pix.rotation + random.randint(15, 45))
    spin.setEndValue(pix.rotation)

    scale = QPropertyAnimation(node, b'scale')
    scale.setDuration(sync)
    scale.setStartValue(node.pix.scale)
    scale.setEndValue(pix.scale)

    opacity = QPropertyAnimation(node, b'opacity')
    opacity.setDuration(sync)
    opacity.setStartValue(node.pix.opacity())
    opacity.setEndValue(1)

    group = QParallelAnimationGroup()

    group.addAnimation(reprise)
    group.addAnimation(spin)
    group.addAnimation(scale)
    group.addAnimation(opacity)

    return group
Example #11
0
 def __createPlaylistCards(self):
     """ 创建播放列表卡 """
     # 创建并行动画组
     self.hideCheckBoxAniGroup = QParallelAnimationGroup(self)
     self.hideCheckBoxAni_list = []
     for playlist in self.playlists:
         self.__createOnePlaylistCard(playlist)
Example #12
0
 def _initAnimations(self):
     '''动画效果'''
     if hasattr(self, "_animationGroup"):
         return  # 由于showEvent的关系,这里要防止多次实例化
     self._animationGroup = QParallelAnimationGroup(self)  # 并行动画
     # 标题栏
     self._animationTitleBar = QPropertyAnimation(
         self._titleBar, b"geometry", self, easingCurve=QEasingCurve.OutBounce, duration=1000)
     # 菜单栏
     self._animationMenuWidget = QPropertyAnimation(
         self._menuWidget, b"geometry", self, easingCurve=QEasingCurve.OutBounce, duration=1000)
     # 链接
     self._animationLinkWidget = QPropertyAnimation(
         self._linkWidget, b"geometry", self, easingCurve=QEasingCurve.OutBounce, duration=1000)
     # 内容
     self._animationContentWidget = QPropertyAnimation(
         self._contentWidget, b"geometry", self, easingCurve=QEasingCurve.OutBounce, duration=1000)
     # add to group
     self._animationGroup.addAnimation(self._animationTitleBar)
     self._animationGroup.addAnimation(self._animationMenuWidget)
     self._animationGroup.addAnimation(self._animationLinkWidget)
     self._animationGroup.addAnimation(self._animationContentWidget)
     # 初始化位置
     self._initAnimationsValues(True)
     # 启动动画效果
     self._animationGroup.start()
Example #13
0
    def __init__(self, songInfo: dict, songCardType, parent=None):
        """ 实例化歌曲卡

        Parameters
        ----------
        songInfo: dict
            歌曲信息字典

        songCardType: `~SongCardType`
            歌曲卡类型

        parent:
            父级
        """
        super().__init__(parent)
        self._getInfo(songInfo)
        self.__resizeTime = 0
        self.__songCardType = songCardType
        # 歌曲卡类型
        self.__SongNameCard = [SongTabSongNameCard,
                               TrackNumSongNameCard][songCardType.value]
        # 初始化各标志位
        self.isSongExist = True
        self.isPlaying = False
        self.isSelected = False
        self.isChecked = False
        self.isInSelectionMode = False
        self.isDoubleClicked = False
        # 记录songCard对应的item的下标
        self.itemIndex = None
        # 创建小部件
        if self.__songCardType == SongCardType.SONG_TAB_SONG_CARD:
            self.songNameCard = self.__SongNameCard(self.songName, self)
        elif self.__songCardType == SongCardType.ALBUM_INTERFACE_SONG_CARD:
            self.songNameCard = self.__SongNameCard(self.songName,
                                                    self.tracknumber, self)
        self.__referenceWidgets()
        # 初始化小部件列表
        self.__scaleableLabelTextWidth_list = []  # 可拉伸的标签的文本的宽度列表
        self.__scaleableWidgetMaxWidth_list = []  # 可拉伸部件的最大宽度列表
        self.__dynamicStyleLabel_list = []
        self.__scaleableWidget_list = []
        self.__clickableLabel_list = []
        self.__labelSpacing_list = []
        self.__label_list = []
        self.__widget_list = []  # 存放所有的小部件
        # 创建动画组和动画列表
        self.aniGroup = QParallelAnimationGroup(self)
        self.__aniWidget_list = []
        self.__deltaX_list = []
        self.ani_list = []
        # 安装事件过滤器
        self.installEventFilter(self)
        # 信号连接到槽
        self.playButton.clicked.connect(self.playButtonSlot)
        self.addToButton.clicked.connect(self.__showAddToMenu)
        self.checkBox.stateChanged.connect(self.checkedStateChangedSlot)
Example #14
0
 def __init__(self, parent=None):
     super(SlidingStackedWidget, self).__init__(parent)
     self.animationEasingCurve = QEasingCurve.Linear
     self.animationDuration = 250
     self.verticalMode = False
     self.wrap = False
     self._active = False
     self._animation_group = QParallelAnimationGroup()
     self._animation_group.finished.connect(self._SH_AnimationGroupFinished)
Example #15
0
    def createAnimation(self, target, index):
        '''创建动画'''
        # 暂停动画一
        PauseAnimation1 = QPauseAnimation(target)
        PauseAnimation1.setDuration(150 * index)

        # 并行动画组一
        # #透明度动画一
        OpacityAnimation1 = QPropertyAnimation(target, b"opacity")
        OpacityAnimation1.setDuration(400)
        OpacityAnimation1.setStartValue(0)
        OpacityAnimation1.setEndValue(1)
        # #移动动画一
        MoveAnimation1 = _MoveAnimation(target, self.parent, self.easing)
        MoveAnimation1.setMoveType(_MoveAnimation.MOVE1)
        MoveAnimation1.setDuration(400)
        MoveAnimation1.setStartValue(QPoint(0, 0))
        MoveAnimation1.setEndValue(QPoint(self.parent.width() / 4.0, 0))
        # 添加到并行动画里面
        ParallelAnimation1 = QParallelAnimationGroup()
        ParallelAnimation1.addAnimation(OpacityAnimation1)
        ParallelAnimation1.addAnimation(MoveAnimation1)

        # 移动动画二
        MoveAnimation2 = _MoveAnimation(target, self.parent, self.easing)
        MoveAnimation2.setMoveType(_MoveAnimation.MOVE2)
        MoveAnimation2.setDuration(2000)
        MoveAnimation2.setEndValue(QPoint((self.parent.width() / 4.0) * 3.0, 0))

        # 并行动画组二
        # #透明度动画二
        OpacityAnimation2 = QPropertyAnimation(target, b"opacity")
        OpacityAnimation2.setDuration(400)
        OpacityAnimation2.setStartValue(1)
        OpacityAnimation2.setEndValue(0)
        # #移动动画三
        MoveAnimation3 = _MoveAnimation(target, self.parent, self.easing)
        MoveAnimation3.setMoveType(_MoveAnimation.MOVE3)
        MoveAnimation3.setDuration(400)
        MoveAnimation3.setEndValue(QPoint(self.parent.width(), 0))
        # 添加到并行动画里面
        ParallelAnimation2 = QParallelAnimationGroup()
        ParallelAnimation2.addAnimation(OpacityAnimation2)
        ParallelAnimation2.addAnimation(MoveAnimation3)

        # 暂停动画二
        PauseAnimation2 = QPauseAnimation(target)
        PauseAnimation2.setDuration(150 * (5 - index - 1))

        # 串行动画组
        self.setLoopCount(-1)    # 无限循环
        self.addAnimation(PauseAnimation1)
        self.addAnimation(ParallelAnimation1)
        self.addAnimation(MoveAnimation2)
        self.addAnimation(ParallelAnimation2)
        self.addAnimation(PauseAnimation2)
Example #16
0
    def __init__(self, header, normal_icon="", hovered_icon="", selected_icon=""):
        QWidget.__init__(self)
        self.is_expanded = False
        self.text = header
        self.label_normal_color = self.palette().link().color().name()
        self.label_hovered_color = self.palette().highlight().color().name()
        self.label_selected_color = self.palette().highlightedText().color().name()
        self.normal_color = self.palette().base().color().name()
        self.selected_color = self.palette().highlight().color()
        self.hovered_color = self.palette().alternateBase().color()

        self.setCursor(Qt.PointingHandCursor)

        if normal_icon:
            self.normal_icon = QImage(normal_icon)
        if hovered_icon:
            self.hovered_icon = QImage(hovered_icon)
        if selected_icon:
            self.selected_icon = QImage(selected_icon)

        self.setAttribute(Qt.WA_Hover, True)

        self.color = self.normal_color
        self.setAutoFillBackground(True)

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        self.icon = QLabel()
        self.icon.setPixmap(QPixmap.fromImage(self.normal_icon))
        self.hyper = QLabel()
        self.hyper.setText("<a style=\"color: " + self.label_normal_color + " text-decoration: none\" href=\"#\">" + self.text + "</a>")
        hbox.addWidget(self.icon)
        hbox.addSpacing(5)
        hbox.addWidget(self.hyper)
        hbox.addStretch()
        hbox.setContentsMargins(8, 8, 8, 8)
        vbox.addLayout(hbox)
        self.content = QWidget()
        self.content.setStyleSheet("background-color: " + self.palette().base().color().name())
        self.content.setMaximumHeight(0)

        vbox.addWidget(self.content)
        vbox.setContentsMargins(0, 0, 0, 0)
        self.setLayout(vbox)

        self.hyper.linkActivated.connect(self.buttonClicked)

        self.anim = QParallelAnimationGroup()
        self.height_anim = QPropertyAnimation(self.content, "maximumHeight".encode("utf-8"))
        self.color_anim = QPropertyAnimation(self, "color".encode("utf-8"))
        self.height_anim.setDuration(200)
        self.color_anim.setDuration(200)
        self.anim.addAnimation(self.height_anim)
        self.anim.addAnimation(self.color_anim)
Example #17
0
    def __init__(self,
                 Title="",
                 parent=None,
                 defaultLayout=False,
                 Message=None):
        super().__init__(parent)

        self.toggle_button = QToolButton(text=Title,
                                         checkable=True,
                                         checked=False)
        self.toggle_button.setStyleSheet("QToolButton { border: none; }")
        self.toggle_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toggle_button.setArrowType(Qt.RightArrow)
        self.toggle_button.pressed.connect(self.on_pressed)

        self.toggle_animation = QParallelAnimationGroup(self)

        self.content_area = QScrollArea(maximumHeight=0, minimumHeight=0)
        self.content_area.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Fixed)
        self.content_area.setFrameShape(QFrame.NoFrame)

        lay = QVBoxLayout(self)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.toggle_button)
        lay.addWidget(self.content_area)

        self.toggle_animation.addAnimation(
            QPropertyAnimation(self, b"minimumHeight"))
        self.toggle_animation.addAnimation(
            QPropertyAnimation(self, b"maximumHeight"))
        self.toggle_animation.addAnimation(
            QPropertyAnimation(self.content_area, b"maximumHeight"))

        if defaultLayout:
            lay = QVBoxLayout()
            self.text = QLabel()
            pa = QPalette()
            pa.setColor(pa.Background, Qt.white)
            pa.setColor(pa.Foreground, Qt.black)
            self.text.setAutoFillBackground(True)
            self.text.setPalette(pa)
            self.text.setTextInteractionFlags(Qt.TextSelectableByMouse)
            self.text.setTextFormat(Qt.MarkdownText)
            self.text.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
            self.text.setWordWrap(True)
            if not Message:
                Message = '空'
            self.text.setText(Message.replace('\n', '\n\n') + '\n')
            lay.addWidget(self.text)
            self.setContentLayout(lay)
Example #18
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)
Example #19
0
File: CustomUI.py Project: ag-sd/py
 def __init__(self, title="", parent=None, animation_duration=300):
     """
     References:
         # Adapted from c++ version
         http://stackoverflow.com/questions/32476006/how-to-make-an-expandable-collapsable-section-widget-in-qt
     """
     super(CollapsibleWidget, self).__init__(parent)
     self.title = title
     self.toggle_button = QToolButton()
     self.toggle_animation = QParallelAnimationGroup(self)
     self.content_area = QScrollArea()
     self.animation_duration = animation_duration
     self._init_base_ui()
Example #20
0
    def __init__(self):
        super(Robot, self).__init__()

        self.setFlag(self.ItemHasNoContents)

        self.torsoItem = RobotTorso(self)
        self.headItem = RobotHead(self.torsoItem)
        self.upperLeftArmItem = RobotLimb(self.torsoItem)
        self.lowerLeftArmItem = RobotLimb(self.upperLeftArmItem)
        self.upperRightArmItem = RobotLimb(self.torsoItem)
        self.lowerRightArmItem = RobotLimb(self.upperRightArmItem)
        self.upperRightLegItem = RobotLimb(self.torsoItem)
        self.lowerRightLegItem = RobotLimb(self.upperRightLegItem)
        self.upperLeftLegItem = RobotLimb(self.torsoItem)
        self.lowerLeftLegItem = RobotLimb(self.upperLeftLegItem)

        settings = (
            #    Item                       Position        Rotation  Scale
            #                                x     y    start    end
            (self.headItem, 0, -18, 20, -20, 1.1),
            (self.upperLeftArmItem, -15, -10, 190, 180, 0),
            (self.lowerLeftArmItem, 30, 0, 50, 10, 0),
            (self.upperRightArmItem, 15, -10, 300, 310, 0),
            (self.lowerRightArmItem, 30, 0, 0, -70, 0),
            (self.upperRightLegItem, 10, 32, 40, 120, 0),
            (self.lowerRightLegItem, 30, 0, 10, 50, 0),
            (self.upperLeftLegItem, -10, 32, 150, 80, 0),
            (self.lowerLeftLegItem, 30, 0, 70, 10, 0),
            (self.torsoItem, 0, 0, 5, -20, 0),
        )

        animation = QParallelAnimationGroup(self)
        for item, pos_x, pos_y, start_rot, end_rot, scale in settings:
            item.setPos(pos_x, pos_y)

            rot_animation = QPropertyAnimation(item, b"rotation")
            rot_animation.setStartValue(start_rot)
            rot_animation.setEndValue(end_rot)
            rot_animation.setEasingCurve(QEasingCurve.SineCurve)
            rot_animation.setDuration(2000)
            animation.addAnimation(rot_animation)

            if scale > 0:
                scale_animation = QPropertyAnimation(item, b"scale")
                scale_animation.setEndValue(scale)
                scale_animation.setEasingCurve(QEasingCurve.SineCurve)
                scale_animation.setDuration(2000)
                animation.addAnimation(scale_animation)

        animation.setLoopCount(-1)
        animation.start()
Example #21
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.mainLayout = QGridLayout()
        self.toggleButton = QToolButton()
        self.toggleAnimation = QParallelAnimationGroup()
        self.contentArea = QScrollArea()
        self.headerLine = QFrame()
        self.animationDuration = 300
        self.checked = False

        self.toggleButton.setStyleSheet("QToolButton { border: none; }")
        self.toggleButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toggleButton.setArrowType(Qt.ArrowType.RightArrow)
        self.toggleButton.setText("Title")
        self.toggleButton.setCheckable(True)
        self.toggleButton.setChecked(False)

        self.headerLine.setFrameShape(QFrame.HLine)
        self.headerLine.setFrameShadow(QFrame.Sunken)
        self.headerLine.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Maximum)

        self.contentArea.setStyleSheet(
            "QScrollArea { background-color: white; border: none; }")
        self.contentArea.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)

        self.contentArea.setMaximumHeight(0)
        self.contentArea.setMinimumHeight(0)

        # let the entire widget grow and shrink with its content
        self.toggleAnimation.addAnimation(QPropertyAnimation())
        self.toggleAnimation.addAnimation(QPropertyAnimation(self))
        self.toggleAnimation.addAnimation(
            QPropertyAnimation(self, b"minimumHeight"))
        self.toggleAnimation.addAnimation(
            QPropertyAnimation(self, b"maximumHeight"))
        self.toggleAnimation.addAnimation(
            QPropertyAnimation(self.contentArea, b"maximumHeight"))

        # don't waste space
        self.mainLayout.setVerticalSpacing(0)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        row = 0
        self.mainLayout.addWidget(self.toggleButton, 0, 0, 1, 1, Qt.AlignLeft)
        self.mainLayout.addWidget(self.headerLine, 0, 2, 1, 1)
        self.mainLayout.addWidget(self.contentArea, 1, 0, 1, 3)
        self.setLayout(self.mainLayout)

        self.toggleButton.clicked.connect(self, SLOT("onBtnClicked(c)"))
 def __init__(self, *args, **kwargs):
     super(QtBubbleLabel, self).__init__(*args, **kwargs)
     self.setWindowFlags(Qt.Window | Qt.Tool | Qt.FramelessWindowHint
                         | Qt.WindowStaysOnTopHint
                         | Qt.X11BypassWindowManagerHint)
     self.setMinimumWidth(200)
     self.setMinimumHeight(48)
     self.setAttribute(Qt.WA_TranslucentBackground, True)
     layout = QVBoxLayout(self)
     layout.setContentsMargins(8, 8, 8, 16)
     self.label = QLabel(self)
     layout.addWidget(self.label)
     self._desktop = QApplication.instance().desktop()
     self.animationGroup = QParallelAnimationGroup(self)
Example #23
0
File: ui.py Project: xmye/games
 def __init__(self, qTetris: 'QTetris', tetrimino: Tetris.Tetrimino,
              tile: Tetris.Tile):
     super(QTetris.QTile, self).__init__()
     tile.delegate = self
     self.color = self.colorMap[type(tetrimino)]
     self.qTetris = qTetris
     self.moveAnimation = QParallelAnimationGroup()
     self.dropAnimation = QPropertyAnimation(self, b'pos')
     self.collapseAnimation = QPropertyAnimation(self, b'pos')
     self.shiftAnimation = QPropertyAnimation(self, b'pos')
     self.collapseAnimation.finished.connect(
         lambda tl=tile: tile.delegate.disappeared(tl))
     self.qTetris.scene.addItem(self)
     self.setPos(QPointF(0, 4))
     self.moved(tile)
 def _initAnimation(self):
     """初始化当前页和下一页的动画变量"""
     # 当前页的动画
     self._animnow = QPropertyAnimation(
         self, propertyName=b'pos', duration=self._speed,
         easingCurve=self._easing)
     # 下一页的动画
     self._animnext = QPropertyAnimation(
         self, propertyName=b'pos', duration=self._speed,
         easingCurve=self._easing)
     # 并行动画组
     self._animgroup = QParallelAnimationGroup(
         self, finished=self.animationDoneSlot)
     self._animgroup.addAnimation(self._animnow)
     self._animgroup.addAnimation(self._animnext)
Example #25
0
 def _initAnimation(self):
     """Initialize the animation variables of the current page and the next page"""
     # Current page animation
     self._animnow = QPropertyAnimation(
         self, propertyName=b'pos', duration=self._speed,
         easingCurve=self._easing)
     # Next page animation
     self._animnext = QPropertyAnimation(
         self, propertyName=b'pos', duration=self._speed,
         easingCurve=self._easing)
     # Parallel animation group
     self._animgroup = QParallelAnimationGroup(
         self, finished=self.animationDoneSlot)
     self._animgroup.addAnimation(self._animnow)
     self._animgroup.addAnimation(self._animnext)
Example #26
0
    def __init__(self, text, pixmap=None, parent=None):
        super().__init__(parent)

        rgb_value = 255 if options.theme == 'dark' else 0
        self.theme = options.theme

        # You are supposed to set size policy like this, and not to override sizePolicy()
        # If vertical policy was preferred, then you would have to implement minimumSizeHint and
        # maximumSize to limit how much the item can shrink and grow.
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        self.text = text
        self.pixmap = pixmap
        self._prepare_pixmap(QColor(rgb_value, rgb_value, rgb_value, 200))
        self.spacing = 12
        self.font = QApplication.font()
        self.font.setBold(True)
        self.fm = QFontMetrics(self.font)
        self.mouse_over = False
        self.checked = False
        self.active = False
        self.setMouseTracking(True)

        self.background_color = QColor(rgb_value, rgb_value, rgb_value, 0)
        self.background_animation = QPropertyAnimation(self, b'opacity')
        self.background_animation.setStartValue(0)
        self.background_animation.setEndValue(40)
        self.background_animation.setDuration(300)

        self.indicator_pos = 5
        self.indicator_position_anim = QPropertyAnimation(
            self, b'indicator_position')
        self.indicator_position_anim.setStartValue(5)
        self.indicator_position_anim.setEndValue(-5)
        self.indicator_position_anim.setDuration(300)

        self.indicator_background = QColor(rgb_value, rgb_value, rgb_value, 0)
        self.indicator_opacity_anim = QPropertyAnimation(
            self, b'indicator_opacity')
        self.indicator_opacity_anim.setStartValue(0)
        self.indicator_opacity_anim.setEndValue(140)
        self.indicator_opacity_anim.setDuration(300)

        self.all_animations = QParallelAnimationGroup()
        self.all_animations.addAnimation(self.background_animation)
        self.all_animations.addAnimation(self.indicator_position_anim)
        self.all_animations.addAnimation(self.indicator_opacity_anim)

        OptionEventChannel.subscribe('theme', self.handle_theme_change)
Example #27
0
    def __init__(self):
        super(Robot, self).__init__()

        self.setFlag(self.ItemHasNoContents)

        self.torsoItem = RobotTorso(self)
        self.headItem = RobotHead(self.torsoItem)
        self.upperLeftArmItem = RobotLimb(self.torsoItem)
        self.lowerLeftArmItem = RobotLimb(self.upperLeftArmItem)
        self.upperRightArmItem = RobotLimb(self.torsoItem)
        self.lowerRightArmItem = RobotLimb(self.upperRightArmItem)
        self.upperRightLegItem = RobotLimb(self.torsoItem)
        self.lowerRightLegItem = RobotLimb(self.upperRightLegItem)
        self.upperLeftLegItem = RobotLimb(self.torsoItem)
        self.lowerLeftLegItem = RobotLimb(self.upperLeftLegItem)

        settings = (
            #    Item                       Position        Rotation  Scale
            #                                x     y    start    end
            (self.headItem, 0, -18, 20, -20, 1.1),
            (self.upperLeftArmItem, -15, -10, 190, 180, 0),
            (self.lowerLeftArmItem, 30, 0, 50, 10, 0),
            (self.upperRightArmItem, 15, -10, 300, 310, 0),
            (self.lowerRightArmItem, 30, 0, 0, -70, 0),
            (self.upperRightLegItem, 10, 32, 40, 120, 0),
            (self.lowerRightLegItem, 30, 0, 10, 50, 0),
            (self.upperLeftLegItem, -10, 32, 150, 80, 0),
            (self.lowerLeftLegItem, 30, 0, 70, 10, 0),
            (self.torsoItem, 0, 0, 5, -20, 0),
        )

        animation = QParallelAnimationGroup(self)
        for item, pos_x, pos_y, start_rot, end_rot, scale in settings:
            item.setPos(pos_x, pos_y)

            rot_animation = QPropertyAnimation(item, b"rotation")
            rot_animation.setStartValue(start_rot)
            rot_animation.setEndValue(end_rot)
            rot_animation.setEasingCurve(QEasingCurve.SineCurve)
            rot_animation.setDuration(2000)
            animation.addAnimation(rot_animation)

            if scale > 0:
                scale_animation = QPropertyAnimation(item, b"scale")
                scale_animation.setEndValue(scale)
                scale_animation.setEasingCurve(QEasingCurve.SineCurve)
                scale_animation.setDuration(2000)
                animation.addAnimation(scale_animation)

        animation.setLoopCount(-1)
        animation.start()
Example #28
0
 def __init__(self, parent=None, playlist=None):
     super().__init__(parent)
     self.shiftLeftTime = 0
     self.shiftRightTime = 0
     # 引用播放列表
     self.playlist = playlist
     self.currentIndex = 0
     self.songInfoCard_list = []
     # 设置发送信号标志位
     self.needToEmitSignal = True
     # 创建并行动画组
     self.parallelAniGroup = QParallelAnimationGroup(self)
     # 记录有待完成的动画
     self.__unCompleteShift_list = []
     # 初始化
     self.__initWidget()
     self.now = QDateTime.currentDateTime().toMSecsSinceEpoch()
Example #29
0
 def __init__(self, source, parent=None):
     super().__init__(parent)
     self.source = source
     self.active = 0
     self.is_limited = False
     self.limit = 4 if self.source is BtnSource.HUNDREDS else 10
     self.setMinimumSize(100, 105 + self.limit * 50)
     self.anim_gp = QParallelAnimationGroup()
     self.anim_gp.finished.connect(self.post_animation)
     y_offset = 55
     self.digits = []
     self.digits_pos = [idx for idx in range(self.limit)]
     for digit in range(self.limit):
         tmp_btn = AngleButton(digit, self)
         tmp_btn.move(0, y_offset)
         y_offset = y_offset + 50
         tmp_btn.pressed.connect(self.switch_active)
         self.digits.append(tmp_btn)
Example #30
0
 def __createAnimations(self):
     """ 创建动画 """
     self.aniGroup = QParallelAnimationGroup(self)
     self.__deltaX_list = [13, 5, -3, -11, -13]
     self.__aniWidget_list = [
         self.songNameCard, self.songerLabel, self.albumLabel,
         self.yearLabel, self.durationLabel
     ]
     self.__ani_list = [
         QPropertyAnimation(widget, b'geometry')
         for widget in self.__aniWidget_list
     ]
     for ani in self.__ani_list:
         ani.setDuration(400)
         ani.setEasingCurve(QEasingCurve.OutQuad)
         self.aniGroup.addAnimation(ani)
     # 记录下移动目标位置
     self.__getAniTargetX_list()
    def animate(self, item):
        self.row = item.row()

        # create a cell widget to get the right position in the table
        self.sourcewidget = QWidget()
        self.list.setCellWidget(self.row, 1, self.sourcewidget)
        pos = self.sourcewidget.mapTo(self, QPoint(0, 0))

        self.editor.setParent(self)
        self.editor.move(pos)
        self.editor.resize(self.sourcewidget.size())
        self.editor.show()

        self.animationgroup = QParallelAnimationGroup()
        self.animx = QPropertyAnimation()
        self.animx.setDuration(300)
        self.animx.setStartValue(pos.x())
        self.animx.setEndValue(0)
        self.animx.setTargetObject(self.editor)
        self.animx.setPropertyName("x".encode("utf-8"))
        self.animationgroup.addAnimation(self.animx)
        self.animy = QPropertyAnimation()
        self.animy.setDuration(300)
        self.animy.setStartValue(pos.y())
        self.animy.setEndValue(0)
        self.animy.setTargetObject(self.editor)
        self.animy.setPropertyName("y".encode("utf-8"))
        self.animationgroup.addAnimation(self.animy)
        self.animw = QPropertyAnimation()
        self.animw.setDuration(300)
        self.animw.setStartValue(self.sourcewidget.size().width())
        self.animw.setEndValue(self.size().width())
        self.animw.setTargetObject(self.editor)
        self.animw.setPropertyName("width".encode("utf-8"))
        self.animationgroup.addAnimation(self.animw)
        self.animh = QPropertyAnimation()
        self.animh.setDuration(300)
        self.animh.setStartValue(self.sourcewidget.size().height())
        self.animh.setEndValue(self.size().height())
        self.animh.setTargetObject(self.editor)
        self.animh.setPropertyName("height".encode("utf-8"))
        self.animationgroup.addAnimation(self.animh)
        self.animationgroup.finished.connect(self.animationFineshedZoomIn)
        self.animationgroup.start()
def login_animate(parent, color):
    parent.parallel_animation_group = QParallelAnimationGroup()
    parent.anim = None
    for i in range(4):
        parent.anim = QPropertyAnimation(parent.pieces[color][i], b"geometry")
        parent.anim.setDuration(1000)
        parent.anim.setEndValue(parent.bases[color][i].geometry())
        parent.parallel_animation_group.addAnimation(parent.anim)

    parent.parallel_animation_group.start()
Example #33
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)
Example #34
0
 def start_card_switch(self, card_to_show):
     self.slide_out_animation = QPropertyAnimation(self.active_card, "geometry")
     self.slide_out_animation.setDuration(ANIMATION_DURATION)
     self.slide_out_animation.setEasingCurve(QEasingCurve.OutCubic)
     self.slide_out_animation.setStartValue(self.visible_geometry)
     self.slide_out_animation.setEndValue(self.hidden_geometry)
     self.set_card_hidden(card_to_show)
     self.slide_in_animation = QPropertyAnimation(card_to_show, "geometry")
     self.slide_in_animation.setDuration(ANIMATION_DURATION)
     self.slide_in_animation.setEasingCurve(QEasingCurve.InCubic)
     self.slide_in_animation.setStartValue(self.hidden_geometry)
     self.slide_in_animation.setEndValue(self.visible_geometry)
     self.animation_group = QParallelAnimationGroup()
     self.animation_group.addAnimation(self.slide_out_animation)
     self.animation_group.addAnimation(self.slide_in_animation)
     self.animation_group.start()
Example #35
0
class Preferences(QDialog):
    # Signal to warn that the window is closed
    settingsClosed = pyqtSignal()

    def __init__(self, parent=None):
        super(Preferences, self).__init__(parent)

        # Main container
        # This contains a grid
        main_box = QVBoxLayout(self)
        main_box.setContentsMargins(200, 50, 200, 100)

        # The grid contains two containers
        # left container and right container
        grid = QGridLayout()

        # Left Container
        left_container = QVBoxLayout()
        left_container.setContentsMargins(0, 0, 0, 0)

        # General
        group_gral = QGroupBox(self.tr("General"))
        box_gral = QVBoxLayout(group_gral)
        # Updates
        btn_updates = QPushButton(self.tr("Check for updates"))
        box_gral.addWidget(btn_updates)
        # Language
        group_language = QGroupBox(self.tr("Language"))
        box = QVBoxLayout(group_language)
        # Find .qm files in language path
        available_langs = file_manager.get_files_from_folder(
            settings.LANGUAGE_PATH)

        languages = ["English"] + available_langs
        self._combo_lang = QComboBox()
        box.addWidget(self._combo_lang)
        self._combo_lang.addItems(languages)
        self._combo_lang.currentIndexChanged[int].connect(
            self._change_lang)
        if PSetting.LANGUAGE:
            self._combo_lang.setCurrentText(PSetting.LANGUAGE)
        box.addWidget(QLabel(self.tr("(Requires restart)")))

        # Add widgets
        left_container.addWidget(group_gral)
        left_container.addWidget(group_language)
        left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                           QSizePolicy.Expanding))

        # Right Container
        right_container = QVBoxLayout()
        right_container.setContentsMargins(0, 0, 0, 0)

        # Editor
        editor_group = QGroupBox(self.tr("Editor Configurations"))
        box_editor = QHBoxLayout(editor_group)
        # Current line
        self._highlight_current_line = QCheckBox(
            self.tr("Highlight Current Line"))
        self._highlight_current_line.setChecked(
            PSetting.HIGHLIGHT_CURRENT_LINE)
        self._highlight_current_line.stateChanged[int].connect(
            self.__current_line_value_changed)
        box_editor.addWidget(self._highlight_current_line)
        # Matching paren
        self._matching_paren = QCheckBox(self.tr("Matching Parenthesis"))
        self._matching_paren.setChecked(
            PSetting.MATCHING_PARENTHESIS)
        self._matching_paren.stateChanged[int].connect(
            self.__set_enabled_matching_parenthesis)
        box_editor.addWidget(self._matching_paren)
        # Font group
        font_group = QGroupBox(self.tr("Font"))
        font_grid = QGridLayout(font_group)
        font_grid.addWidget(QLabel(self.tr("Family")), 0, 0)
        self._combo_font = QFontComboBox()
        self._combo_font.setCurrentFont(PSetting.FONT)
        font_grid.addWidget(self._combo_font, 0, 1)
        font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0)
        self._combo_font_size = QComboBox()
        fdb = QFontDatabase()
        combo_sizes = fdb.pointSizes(PSetting.FONT.family())
        current_size_index = combo_sizes.index(
            PSetting.FONT.pointSize())

        self._combo_font_size.addItems([str(f) for f in combo_sizes])
        self._combo_font_size.setCurrentIndex(current_size_index)
        font_grid.addWidget(self._combo_font_size, 1, 1)

        right_container.addWidget(editor_group)
        right_container.addWidget(font_group)
        right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                            QSizePolicy.Expanding))

        # Add widgets
        grid.addLayout(left_container, 0, 0)
        grid.addLayout(right_container, 0, 1)
        main_box.addLayout(grid)

        # Button close and reset
        hbox = QHBoxLayout()
        hbox.setSpacing(20)
        hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btn_cancel = QPushButton(self.tr("Back"))
        hbox.addWidget(btn_cancel)
        btn_reset = QPushButton(self.tr("Reset Configurations"))
        hbox.addWidget(btn_reset)
        main_box.addLayout(hbox)

        # Overlay
        self.overlay = overlay_widget.OverlayWidget(self)
        self.overlay.hide()

        # Effect and animations
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        duration, x = 180, 150  # Animation duration
        # Animation start
        # Opacity animation
        self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_s.setDuration(duration)
        self.opacity_animation_s.setStartValue(0.0)
        self.opacity_animation_s.setEndValue(1.0)
        # X animation
        self.x_animation_s = QPropertyAnimation(self, b"geometry")
        self.x_animation_s.setDuration(duration)
        self.x_animation_s.setStartValue(QRect(x, 0, parent.width(),
                                               parent.height()))
        self.x_animation_s.setEndValue(QRect(0, 0, parent.width(),
                                             parent.height()))
        # Animation end
        # Opacity animation
        self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_e.setDuration(duration)
        self.opacity_animation_e.setStartValue(1.0)
        self.opacity_animation_e.setEndValue(0.0)
        # X animation
        self.x_animation_e = QPropertyAnimation(self, b"geometry")
        self.x_animation_e.setDuration(duration)
        self.x_animation_e.setStartValue(QRect(0, 0, parent.width(),
                                               parent.height()))
        self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(),
                                             parent.height()))

        # Group animation start
        self.group_animation_s = QParallelAnimationGroup()
        self.group_animation_s.addAnimation(self.opacity_animation_s)
        self.group_animation_s.addAnimation(self.x_animation_s)

        # Group animation end
        self.group_animation_e = QParallelAnimationGroup()
        self.group_animation_e.addAnimation(self.opacity_animation_e)
        self.group_animation_e.addAnimation(self.x_animation_e)

        # Connections
        self.group_animation_e.finished.connect(
            self._on_group_animation_finished)
        btn_cancel.clicked.connect(self.close)
        btn_reset.clicked.connect(self._reset_settings)
        btn_updates.clicked.connect(self._check_for_updates)
        # self.thread.finished.connect(self._on_thread_finished)
        self._combo_font.currentFontChanged.connect(
            self._change_font)
        self._combo_font_size.currentTextChanged.connect(
            self._change_font_size)

    def __current_line_value_changed(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('highlight_current_line', value)
        PSetting.HIGHLIGHT_CURRENT_LINE = value

    def __set_enabled_matching_parenthesis(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue("matching_parenthesis", value)
        PSetting.MATCHING_PARENTHESIS = value

    def _change_font(self, font):
        # FIXME: un quilombo esto
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def _change_font_size(self, size):
        # FIXME: un quilombo esto
        font = self._combo_font.currentFont()
        font.setPointSize(int(size))
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def showEvent(self, event):
        super(Preferences, self).showEvent(event)
        self.group_animation_s.start()

    def resizeEvent(self, event):
        self.overlay.resize(self.size())
        event.accept()

    def done(self, result):
        self.res = result
        self.group_animation_e.start()

    def _on_group_animation_finished(self):
        super(Preferences, self).done(self.res)
        self.settingsClosed.emit()

    def _check_for_updates(self):
        # Thread
        self._thread = QThread()
        self._updater = updater.Updater()
        self._updater.moveToThread(self._thread)
        self._thread.started.connect(self._updater.check_updates)
        self._updater.finished.connect(self.__on_thread_update_finished)
        # Show overlay widget
        self.overlay.show()
        # Start thread
        self._thread.start()

    def __on_thread_update_finished(self):
        # Hide overlay widget
        self.overlay.hide()
        self._thread.quit()
        msg = QMessageBox(self)
        if not self._updater.error:
            if self._updater.version:
                version = self._updater.version
                msg.setWindowTitle(self.tr("New version available!"))
                msg.setText(self.tr("Check the web site to "
                                    "download <b>Pireal {}</b>".format(
                                        version)))
                download_btn = msg.addButton(self.tr("Download!"),
                                             QMessageBox.YesRole)
                msg.addButton(self.tr("Cancel"),
                              QMessageBox.RejectRole)
                msg.exec_()
                r = msg.clickedButton()
                if r == download_btn:
                    webbrowser.open_new(
                        "http://centaurialpha.github.io/pireal")
            else:
                msg.setWindowTitle(self.tr("Information"))
                msg.setText(self.tr("Last version installed"))
                msg.addButton(self.tr("Ok"),
                              QMessageBox.AcceptRole)
                msg.exec_()
        else:
            msg.critical(self, self.tr("Error"),
                         self.tr("Connection error"))

        self._thread.deleteLater()
        self._updater.deleteLater()

    def _reset_settings(self):
        """ Remove all settings """

        msg = QMessageBox(self)
        msg.setWindowTitle(self.tr("Reset Settings"))
        msg.setText(self.tr("Are you sure you want to clear all settings?"))
        msg.setIcon(QMessageBox.Question)
        msg.addButton(self.tr("No"), QMessageBox.NoRole)
        yes_btn = msg.addButton(self.tr("Yes"),
                                QMessageBox.YesRole)
        msg.exec_()
        r = msg.clickedButton()
        if r == yes_btn:
            QSettings(settings.SETTINGS_PATH, QSettings.IniFormat).clear()
            self.close()

    def _change_lang(self, index):
        lang = self._combo_lang.itemText(index)
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('language', lang)
Example #36
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()
Example #37
0
class CoffeeFundWindow(QWidget):
    signal_back = pyqtSignal()
    signal_coffee = pyqtSignal()
    signal_account = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__()

        self.cards = {}  # type: Dict[GuiCards, QWidget]
        """
            Python's GC will clean up QPropertyAnimations as soon as it leaves the button handler,
             therefore they will appear not to work. Use members to store the animations.
            see http://stackoverflow.com/a/6953965
        """
        self.slide_in_animation = None
        self.slide_out_animation = None
        self.animation_group = None
        self.setObjectName("coffeeFundWindow")

        """
            Store the position and size of visible/hidden cards for the animation sequences
        """
        self.hidden_geometry = None
        self.visible_geometry = None

        layout = QStackedLayout()
        layout.setStackingMode(QStackedLayout.StackAll)

        card_remove = RemoveCard()
        self.cards[GuiCards.RemoveCard] = card_remove
        layout.addWidget(card_remove)

        card_choose_action = ChooseActionCard()
        self.cards[GuiCards.ChooseAction] = card_choose_action
        layout.addWidget(card_choose_action)

        card_account = AccountCard()
        self.cards[GuiCards.AccountInfo] = card_account
        layout.addWidget(card_account)

        # keep this as last initialized card, the last card will be shown on startup!
        card_start = StartCard()
        self.cards[GuiCards.Start] = card_start
        layout.addWidget(card_start)

        self.setLayout(layout)
        self.setWindowTitle("Kaffeekasse")

        layout.setCurrentWidget(card_start)
        self.active_card = None

        card_choose_action.button_account.clicked.connect(self.signal_account)
        card_choose_action.button_coffee.clicked.connect(self.signal_coffee)
        card_account.button_back.clicked.connect(self.signal_back)

    def set_card_hidden(self, card: QWidget):
        card.setGeometry(self.hidden_geometry)

    def show_start(self):
        self.show_card(GuiCards.Start)

    def show_account(self, name, value):
        self.cards[GuiCards.AccountInfo].set_user_name(name)
        self.cards[GuiCards.AccountInfo].set_balance(value)
        self.show_card(GuiCards.AccountInfo)

    def show_choose_action(self, name: str):
        self.cards[GuiCards.ChooseAction].set_user_name(name)
        self.show_card(GuiCards.ChooseAction)

    def show_remove(self):
        self.show_card(GuiCards.RemoveCard)

    def show_card(self, card_id: GuiCards):
        if self.active_card is None:
            self.active_card = self.cards[GuiCards.Start]

        if self.active_card == self.cards[card_id]:
            return

        if self.visible_geometry is None or self.hidden_geometry is None:
            self.visible_geometry = self.active_card.geometry()  # type: QRect
            self.hidden_geometry = QRect(self.visible_geometry.x(), self.visible_geometry.height() * 1.5,
                                         self.visible_geometry.width(), self.visible_geometry.height())
        for key in self.cards.keys():
            if key != self.active_card:
                self.set_card_hidden(self.cards[key])

        card_to_show = self.cards[card_id]
        self.start_card_switch(card_to_show)
        self.active_card = self.cards[card_id]
        self.layout().setCurrentWidget(self.active_card)

    def start_card_switch(self, card_to_show):
        self.slide_out_animation = QPropertyAnimation(self.active_card, "geometry")
        self.slide_out_animation.setDuration(ANIMATION_DURATION)
        self.slide_out_animation.setEasingCurve(QEasingCurve.OutCubic)
        self.slide_out_animation.setStartValue(self.visible_geometry)
        self.slide_out_animation.setEndValue(self.hidden_geometry)
        self.set_card_hidden(card_to_show)
        self.slide_in_animation = QPropertyAnimation(card_to_show, "geometry")
        self.slide_in_animation.setDuration(ANIMATION_DURATION)
        self.slide_in_animation.setEasingCurve(QEasingCurve.InCubic)
        self.slide_in_animation.setStartValue(self.hidden_geometry)
        self.slide_in_animation.setEndValue(self.visible_geometry)
        self.animation_group = QParallelAnimationGroup()
        self.animation_group.addAnimation(self.slide_out_animation)
        self.animation_group.addAnimation(self.slide_in_animation)
        self.animation_group.start()
Example #38
0
    state5 = createGeometryState(button1, QRect(100, 100, 50, 50), button2,
            QRect(150, 100, 50, 50), button3, QRect(100, 150, 50, 50), button4,
            QRect(150, 150, 50, 50), group)

    state6 = createGeometryState(button1, QRect(50, 50, 50, 50), button2,
            QRect(200, 50, 50, 50), button3, QRect(50, 200, 50, 50), button4,
            QRect(200, 200, 50, 50), group)

    state7 = createGeometryState(button1, QRect(0, 0, 50, 50), button2,
            QRect(250, 0, 50, 50), button3, QRect(0, 250, 50, 50), button4,
            QRect(250, 250, 50, 50), group)

    group.setInitialState(state1)

    animationGroup = QParallelAnimationGroup()
    anim = QPropertyAnimation(button4, 'geometry')
    anim.setDuration(1000)
    anim.setEasingCurve(QEasingCurve.OutElastic)
    animationGroup.addAnimation(anim)

    subGroup = QSequentialAnimationGroup(animationGroup)
    subGroup.addPause(100)
    anim = QPropertyAnimation(button3, 'geometry')
    anim.setDuration(1000)
    anim.setEasingCurve(QEasingCurve.OutElastic)
    subGroup.addAnimation(anim)

    subGroup = QSequentialAnimationGroup(animationGroup)
    subGroup.addPause(150)
    anim = QPropertyAnimation(button2, 'geometry')
Example #39
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()
Example #40
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
Example #41
0
    # Ui.
    view = View(scene)
    view.setWindowTitle("Animated Tiles")
    view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
    view.setBackgroundBrush(QBrush(bgPix))
    view.setCacheMode(QGraphicsView.CacheBackground)
    view.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
    view.show()

    states = QStateMachine()
    states.addState(rootState)
    states.setInitialState(rootState)
    rootState.setInitialState(centeredState)

    group = QParallelAnimationGroup()
    for i, item in enumerate(items):
        anim = QPropertyAnimation(item, b'pos')
        anim.setDuration(750 + i * 25)
        anim.setEasingCurve(QEasingCurve.InOutBack)
        group.addAnimation(anim)

    trans = rootState.addTransition(ellipseButton.pressed, ellipseState)
    trans.addAnimation(group)

    trans = rootState.addTransition(figure8Button.pressed, figure8State)
    trans.addAnimation(group)

    trans = rootState.addTransition(randomButton.pressed, randomState)
    trans.addAnimation(group)
Example #42
0
    def __init__(self, parent=None):
        super(Preferences, self).__init__(parent)

        # Main container
        # This contains a grid
        main_box = QVBoxLayout(self)
        main_box.setContentsMargins(200, 50, 200, 100)

        # The grid contains two containers
        # left container and right container
        grid = QGridLayout()

        # Left Container
        left_container = QVBoxLayout()
        left_container.setContentsMargins(0, 0, 0, 0)

        # General
        group_gral = QGroupBox(self.tr("General"))
        box_gral = QVBoxLayout(group_gral)
        # Updates
        btn_updates = QPushButton(self.tr("Check for updates"))
        box_gral.addWidget(btn_updates)
        # Language
        group_language = QGroupBox(self.tr("Language"))
        box = QVBoxLayout(group_language)
        # Find .qm files in language path
        available_langs = file_manager.get_files_from_folder(
            settings.LANGUAGE_PATH)

        languages = ["English"] + available_langs
        self._combo_lang = QComboBox()
        box.addWidget(self._combo_lang)
        self._combo_lang.addItems(languages)
        self._combo_lang.currentIndexChanged[int].connect(
            self._change_lang)
        if PSetting.LANGUAGE:
            self._combo_lang.setCurrentText(PSetting.LANGUAGE)
        box.addWidget(QLabel(self.tr("(Requires restart)")))

        # Add widgets
        left_container.addWidget(group_gral)
        left_container.addWidget(group_language)
        left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                           QSizePolicy.Expanding))

        # Right Container
        right_container = QVBoxLayout()
        right_container.setContentsMargins(0, 0, 0, 0)

        # Editor
        editor_group = QGroupBox(self.tr("Editor Configurations"))
        box_editor = QHBoxLayout(editor_group)
        # Current line
        self._highlight_current_line = QCheckBox(
            self.tr("Highlight Current Line"))
        self._highlight_current_line.setChecked(
            PSetting.HIGHLIGHT_CURRENT_LINE)
        self._highlight_current_line.stateChanged[int].connect(
            self.__current_line_value_changed)
        box_editor.addWidget(self._highlight_current_line)
        # Matching paren
        self._matching_paren = QCheckBox(self.tr("Matching Parenthesis"))
        self._matching_paren.setChecked(
            PSetting.MATCHING_PARENTHESIS)
        self._matching_paren.stateChanged[int].connect(
            self.__set_enabled_matching_parenthesis)
        box_editor.addWidget(self._matching_paren)
        # Font group
        font_group = QGroupBox(self.tr("Font"))
        font_grid = QGridLayout(font_group)
        font_grid.addWidget(QLabel(self.tr("Family")), 0, 0)
        self._combo_font = QFontComboBox()
        self._combo_font.setCurrentFont(PSetting.FONT)
        font_grid.addWidget(self._combo_font, 0, 1)
        font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0)
        self._combo_font_size = QComboBox()
        fdb = QFontDatabase()
        combo_sizes = fdb.pointSizes(PSetting.FONT.family())
        current_size_index = combo_sizes.index(
            PSetting.FONT.pointSize())

        self._combo_font_size.addItems([str(f) for f in combo_sizes])
        self._combo_font_size.setCurrentIndex(current_size_index)
        font_grid.addWidget(self._combo_font_size, 1, 1)

        right_container.addWidget(editor_group)
        right_container.addWidget(font_group)
        right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                            QSizePolicy.Expanding))

        # Add widgets
        grid.addLayout(left_container, 0, 0)
        grid.addLayout(right_container, 0, 1)
        main_box.addLayout(grid)

        # Button close and reset
        hbox = QHBoxLayout()
        hbox.setSpacing(20)
        hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btn_cancel = QPushButton(self.tr("Back"))
        hbox.addWidget(btn_cancel)
        btn_reset = QPushButton(self.tr("Reset Configurations"))
        hbox.addWidget(btn_reset)
        main_box.addLayout(hbox)

        # Overlay
        self.overlay = overlay_widget.OverlayWidget(self)
        self.overlay.hide()

        # Effect and animations
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        duration, x = 180, 150  # Animation duration
        # Animation start
        # Opacity animation
        self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_s.setDuration(duration)
        self.opacity_animation_s.setStartValue(0.0)
        self.opacity_animation_s.setEndValue(1.0)
        # X animation
        self.x_animation_s = QPropertyAnimation(self, b"geometry")
        self.x_animation_s.setDuration(duration)
        self.x_animation_s.setStartValue(QRect(x, 0, parent.width(),
                                               parent.height()))
        self.x_animation_s.setEndValue(QRect(0, 0, parent.width(),
                                             parent.height()))
        # Animation end
        # Opacity animation
        self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_e.setDuration(duration)
        self.opacity_animation_e.setStartValue(1.0)
        self.opacity_animation_e.setEndValue(0.0)
        # X animation
        self.x_animation_e = QPropertyAnimation(self, b"geometry")
        self.x_animation_e.setDuration(duration)
        self.x_animation_e.setStartValue(QRect(0, 0, parent.width(),
                                               parent.height()))
        self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(),
                                             parent.height()))

        # Group animation start
        self.group_animation_s = QParallelAnimationGroup()
        self.group_animation_s.addAnimation(self.opacity_animation_s)
        self.group_animation_s.addAnimation(self.x_animation_s)

        # Group animation end
        self.group_animation_e = QParallelAnimationGroup()
        self.group_animation_e.addAnimation(self.opacity_animation_e)
        self.group_animation_e.addAnimation(self.x_animation_e)

        # Connections
        self.group_animation_e.finished.connect(
            self._on_group_animation_finished)
        btn_cancel.clicked.connect(self.close)
        btn_reset.clicked.connect(self._reset_settings)
        btn_updates.clicked.connect(self._check_for_updates)
        # self.thread.finished.connect(self._on_thread_finished)
        self._combo_font.currentFontChanged.connect(
            self._change_font)
        self._combo_font_size.currentTextChanged.connect(
            self._change_font_size)