示例#1
0
class FaderWidget(QWidget):

    def __init__(self, old_widget, new_widget):
        super(FaderWidget, self).__init__(new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(500)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()

    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
示例#2
0
class FaderWidget(QtWidgets.QWidget):

    pixmap_opacity = 0

    def __init__(self, old_widget, new_widget):

        QtWidgets.QWidget.__init__(self, new_widget)

        self.old_pixmap = QtGui.QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(500)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()

    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
示例#3
0
 def __init__(self, parent=None, wFlags=0):
     super(CustomProxy, self).__init__(parent, wFlags)
     self.popupShown = False
     self.currentPopup = None
     self.timeLine = QTimeLine(250, self)
     self.timeLine.valueChanged.connect(self.updateStep)
     self.timeLine.stateChanged.connect(self.stateChanged)
示例#4
0
        def animate_to(t, item, x, y, angle):
            # The QGraphicsItemAnimation class is used to
            # animate an item in specific ways
            # FIXME QGraphicsItemAnimation class is no longer supported.
            animation = QGraphicsItemAnimation()

            # You create a timeline (in this case, it is 1 second long
            timeline = QTimeLine(1000)

            # And it has 100 steps
            timeline.setFrameRange(0, 100)

            # I want that, at time t, the item be at point x,y
            animation.setPosAt(t, QPointF(x, y))

            # And it should be rotated at angle "angle"
            animation.setRotationAt(t, angle)

            # It should animate this specific item
            animation.setItem(item)

            # And the whole animation is this long, and has
            # this many steps as I set in timeline.
            animation.setTimeLine(timeline)

            # Here is the animation, use it.
            return animation
示例#5
0
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        self.resize(600, 200)
        layout = QVBoxLayout(self)

        # 配置全局属性(也可以通过start方法里的参数配置单独的属性)
        CLoadingBar.config(height=2,
                           direction=CLoadingBar.TOP,
                           color='#2d8cf0',
                           failedColor='#ed4014')

        # 子控件顶部进度
        self.widget1 = QWidget(self)
        layout.addWidget(self.widget1)
        CLoadingBar.start(self.widget1, color='#19be6b', failedColor='#ff9900')

        widget = QWidget(self)
        layoutc = QHBoxLayout(widget)
        layoutc.addWidget(QPushButton('开始', self, clicked=self.doStart))
        layoutc.addWidget(QPushButton('结束', self, clicked=self.doFinish))
        layoutc.addWidget(QPushButton('错误', self, clicked=self.doError))
        layout.addWidget(widget)

        # 子控件底部进度
        self.widget2 = QWidget(self)
        layout.addWidget(self.widget2)
        CLoadingBar.start(self.widget2, direction=CLoadingBar.BOTTOM, height=6)

        # 模拟进度
        self.updateTimer = QTimeLine(10000,
                                     self,
                                     frameChanged=self.doUpdateProgress)
        self.updateTimer.setFrameRange(0, 100)
        # 设置数字变化曲线模拟进度的不规则变化
        self.updateTimer.setCurveShape(QTimeLine.EaseInOutCurve)
示例#6
0
    def __init__(self, parent=None, direction="ltr", rtf=False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(
            lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()
示例#7
0
    def __init__(self):
        super(Demo, self).__init__()
        self.resize(600, 600)

        self.label = QLabel('Hello PyQt5', self)
        self.label.move(-100, 100)

        self.timeline = QTimeLine(5000, self)
        self.timeline.setFrameRange(0, 700)
        self.timeline.frameChanged.connect(self.set_frame_func)
        self.timeline.stateChanged.connect(
            lambda: print(self.timeline.state()))  # 1
        self.timeline.setLoopCount(0)

        self.start_btn = QPushButton('Start', self)
        self.stop_btn = QPushButton('Stop', self)
        self.pause_btn = QPushButton('Pause', self)
        self.resume_btn = QPushButton('Resume', self)

        self.start_btn.clicked.connect(self.timeline.start)  # 2
        self.stop_btn.clicked.connect(self.timeline.stop)
        self.pause_btn.clicked.connect(lambda: self.timeline.setPaused(True))
        self.resume_btn.clicked.connect(self.timeline.resume)

        self.h_layout = QHBoxLayout()
        self.v_layout = QVBoxLayout()
        self.h_layout.addWidget(self.start_btn)
        self.h_layout.addWidget(self.stop_btn)
        self.h_layout.addWidget(self.pause_btn)
        self.h_layout.addWidget(self.resume_btn)
        self.v_layout.addStretch(1)
        self.v_layout.addLayout(self.h_layout)
        self.setLayout(self.v_layout)
示例#8
0
class FaderWidget(QWidget):
    """
    A QWidget that allows for fading in and out on display.
    """
    def __init__(self, old_widget, new_widget):

        QWidget.__init__(self, new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(450)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def paintEvent(self, event):

        painter = QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()

    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
示例#9
0
    def move_to(self, nx_pos):
        """
        Move to corresponding position
        :param nx_pos:
        :return:
        """
        origin_x = self.x()
        origin_y = self.y()
        final_x = nx_pos[self.id][0]
        final_y = nx_pos[self.id][1]

        def frame_move(frame):
            value = self.timeline.valueForTime(self.timeline.currentTime())
            x = origin_x + (final_x - origin_x) * value
            y = origin_y + (final_y - origin_y) * value
            self.setPos(x, y)
            if self.scene():
                self.scene().node_moved.emit(self.id, x, y)

        def timeline_ends():
            self.setPos(final_x, final_y)
            self.timeline = None

        # Remember to hold the references to QTimeLine and QGraphicsItemAnimation instances.
        # They are not kept anywhere, even if you invoke QTimeLine.start().
        self.timeline = QTimeLine(1000)
        self.timeline.setFrameRange(0, 100)
        self.timeline.frameChanged.connect(frame_move)
        self.timeline.finished.connect(timeline_ends)

        self.timeline.start()
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle("Screen and Gaze Capture")
        grid = QGridLayout()
        layout_frame = QFrame()
        layout_frame.setLayout(grid)
        self.setCentralWidget(layout_frame)

        self.tracker_label = QLabel("No eye tracker connected.")
        grid.addWidget(self.tracker_label, 0, 0)

        connect_button = QPushButton("Connect to Eye Tracker")
        connect_button.pressed.connect(connect_to_tracker)
        grid.addWidget(connect_button, 1, 0)

        calibrate_button = QPushButton("Calibrate Eye Tracker")
        calibrate_button.pressed.connect(calibrate)
        grid.addWidget(calibrate_button, 2, 0)

        self.record_button = QPushButton("Record Screen and Gaze")
        self.record_button.pressed.connect(capture_screen)
        grid.addWidget(self.record_button, 3, 0)

        self.author_vid_button = QPushButton("Write Author Video")
        self.author_vid_button.pressed.connect(create_video)
        grid.addWidget(self.author_vid_button, 4, 0)
        self.author_vid_button.setEnabled(False)

        self.timeline = QTimeLine()
        self.timeline.setCurveShape(QTimeLine.LinearCurve)
        self.timeline.setDuration(360000)  #Totsl video lengthn in milliseconds
        self.timeline.setFrameRange(
            0, 7500)  #Maximum Frames in this video as 30 fps
        self.timeline.frameChanged.connect(update_frame)
        self.timeline.setUpdateInterval(10)  #Rate of Frame Capture
示例#11
0
    def setupAnimation(self):

        self.timer = QTimeLine()
        self.timer.setLoopCount(0)
        self.timer.setFrameRange(0, 100)

        self.timer.frameChanged[int].connect(self.doStep)
        self.timer.start()
示例#12
0
 def __init__(self, parent=None):
     super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
     self._timeline = QTimeLine(updateInterval=100,
                                frameChanged=self.setValue)
     self._timeline.setFrameRange(0, 100)
     self._hideTimer = QTimer(timeout=self._done,
                              singleShot=True,
                              interval=3000)
示例#13
0
 def __init__(self, *args, **kwargs):
     super(CCountUp, self).__init__(*args, **kwargs)
     self.isFloat = False  # 是否是小数
     font = self.font() or QFont()
     font.setBold(True)
     self.setFont(font)
     self.timeline = QTimeLine(6000, self)
     self.timeline.setEasingCurve(QEasingCurve.OutExpo)
     self.timeline.frameChanged.connect(self.onFrameChanged)
示例#14
0
 def __init__(self, parent = None):
     super().__init__()
     self.timer = QTimeLine(2000, self)
     #self.address = parent.address
     #self.port = parent.port
     self.address = "127.0.0.1"
     self.port = "5577"
     
     h1 = QHBoxLayout(None)
     self.yourLabel = QLabel(_("Your color:"), self)
     self.blackStone = QRadioButton(_("Black"), self)
     self.blackStone.setChecked(True)
     self.whiteStone = QRadioButton(_("White"), self)
     h1.addWidget(self.yourLabel)
     h1.addWidget(self.blackStone)
     h1.addWidget(self.whiteStone)
     
     h2 = QHBoxLayout(None)
     self.levelLabel = QLabel(_("Gnugo level:"), self)
     self.gnuLevel = QSpinBox(self)
     self.gnuLevel.setRange(1, 10)
     self.gnuLevel.setValue(8)
     h2.addWidget(self.levelLabel)
     h2.addWidget(self.gnuLevel)
     
     h3 = QHBoxLayout(None)
     self.komiLabel = QLabel(_("Set komi:"), self)
     self.komi = QSpinBox(self)
     self.komi.setEnabled(False)
     self.komi.setRange(0, 9)
     self.komi.setValue(0)
     h3.addWidget(self.komiLabel)
     h3.addWidget(self.komi)
     
     h4 = QHBoxLayout(None)
     self.startButton = QPushButton(_("Start Server"), self)
     buttonBox = QDialogButtonBox(self)
     self.okButton = QPushButton(_("OK"))
     self.okButton.setEnabled(False)
     self.cancelButton = QPushButton(_("Cancel"))
     buttonBox.addButton(self.okButton, QDialogButtonBox.AcceptRole)
     buttonBox.addButton(self.cancelButton, QDialogButtonBox.RejectRole)
     h4.addWidget(self.startButton)
     h4.addWidget(buttonBox)
     
     mainLayout = QVBoxLayout(None)
     mainLayout.addLayout(h1)
     mainLayout.addLayout(h2)
     mainLayout.addLayout(h3)
     mainLayout.addLayout(h4)
     self.setLayout(mainLayout)
     
     buttonBox.accepted.connect(self.accept)
     buttonBox.rejected.connect(self.reject)
     self.startButton.clicked.connect(self.startServer)
     self.timer.finished.connect(self.serverStarted)
示例#15
0
class Robot(RobotPart):
    def __init__(self):
        super(Robot, self).__init__()

        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)

        self.timeline = QTimeLine()
        settings = [
            #             item               position    rotation at
            #                                 x    y    time 0  /  1
            (self.headItem, 0, -18, 20, -20),
            (self.upperLeftArmItem, -15, -10, 190, 180),
            (self.lowerLeftArmItem, 30, 0, 50, 10),
            (self.upperRightArmItem, 15, -10, 300, 310),
            (self.lowerRightArmItem, 30, 0, 0, -70),
            (self.upperRightLegItem, 10, 32, 40, 120),
            (self.lowerRightLegItem, 30, 0, 10, 50),
            (self.upperLeftLegItem, -10, 32, 150, 80),
            (self.lowerLeftLegItem, 30, 0, 70, 10),
            (self.torsoItem, 0, 0, 5, -20)
        ]
        self.animations = []
        for item, pos_x, pos_y, rotation1, rotation2 in settings:
            item.setPos(pos_x, pos_y)
            animation = QGraphicsItemAnimation()
            animation.setItem(item)
            animation.setTimeLine(self.timeline)
            animation.setRotationAt(0, rotation1)
            animation.setRotationAt(1, rotation2)
            self.animations.append(animation)
        self.animations[0].setScaleAt(1, 1.1, 1.1)

        self.timeline.setUpdateInterval(1000 / 25)
        self.timeline.setCurveShape(QTimeLine.SineCurve)
        self.timeline.setLoopCount(0)
        self.timeline.setDuration(2000)
        self.timeline.start()

    def boundingRect(self):
        return QRectF()

    def paint(self, painter, option, widget=None):
        pass
示例#16
0
class Robot(RobotPart):
    def __init__(self):
        super(Robot, self).__init__()

        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)

        self.timeline = QTimeLine()
        settings = [
        #             item               position    rotation at
        #                                 x    y    time 0  /  1
            ( self.headItem,              0,  -18,      20,   -20 ),
            ( self.upperLeftArmItem,    -15,  -10,     190,   180 ),
            ( self.lowerLeftArmItem,     30,    0,      50,    10 ),
            ( self.upperRightArmItem,    15,  -10,     300,   310 ),
            ( self.lowerRightArmItem,    30,    0,       0,   -70 ),
            ( self.upperRightLegItem,    10,   32,      40,   120 ),
            ( self.lowerRightLegItem,    30,    0,      10,    50 ),
            ( self.upperLeftLegItem,    -10,   32,     150,    80 ),
            ( self.lowerLeftLegItem,     30,    0,      70,    10 ),
            ( self.torsoItem,             0,    0,       5,   -20 )
        ]
        self.animations = []
        for item, pos_x, pos_y, rotation1, rotation2 in settings: 
            item.setPos(pos_x,pos_y)
            animation = QGraphicsItemAnimation()
            animation.setItem(item)
            animation.setTimeLine(self.timeline)
            animation.setRotationAt(0, rotation1)
            animation.setRotationAt(1, rotation2)
            self.animations.append(animation)
        self.animations[0].setScaleAt(1, 1.1, 1.1)
    
        self.timeline.setUpdateInterval(1000 / 25)
        self.timeline.setCurveShape(QTimeLine.SineCurve)
        self.timeline.setLoopCount(0)
        self.timeline.setDuration(2000)
        self.timeline.start()

    def boundingRect(self):
        return QRectF()

    def paint(self, painter, option, widget=None):
        pass
示例#17
0
    def __init__(self, old_widget, new_widget):

        QWidget.__init__(self, new_widget)
        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0
        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(222)
        self.timeline.start()
        self.resize(new_widget.size())
        self.show()
示例#18
0
    def __init__(self, old_widget, new_widget):

        QWidget.__init__(self, new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)

        self.pixmap_opacity = None
        self.timeline = QTimeLine(333, self)
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)

        self.resize(new_widget.size())
        self.show()
示例#19
0
    def openItem(self, item):
        if item == self.last_item:
            return

        if self.last_item:
            self.closeItem(self.last_item)

        self.animation = QTimeLine(ANIMATE_TIME, self)
        self.animation.setFrameRange(36, EXPANDED_SIZE)
        self.animation.frameChanged.connect(
            lambda x: item.setSizeHint(QSize(32, x)))
        self.animation.start()
        self.last_item = item
        self.animation.finished.connect(
            lambda: self.collectionList.setCurrentItem(item))
 def __init__(self, parent):
     """Init class."""
     super(FaderWidget, self).__init__(parent)
     self.timeline, self.opacity, self.old_pic = QTimeLine(), 1.0, None
     self.timeline.valueChanged.connect(self.animate)
     self.timeline.finished.connect(self.close)
     self.timeline.setDuration(750)  # 500 ~ 750 Ms is Ok, Not more.
示例#21
0
    def move_to(self, nx_pos):
        """
        Move to corresponding position
        :param nx_pos:
        :return:
        """
        origin_x = self.x()
        origin_y = self.y()
        final_x = nx_pos[self.id][0]
        final_y = nx_pos[self.id][1]

        def frame_move(frame):
            value = self.timeline.valueForTime(self.timeline.currentTime())
            x = origin_x + (final_x - origin_x) * value
            y = origin_y + (final_y - origin_y) * value
            self.setPos(x, y)
            self.scene().node_moved.emit(self.id, x, y)

        def timeline_ends():
            self.setPos(final_x, final_y)
            self.timeline = None

        # Remember to hold the references to QTimeLine and QGraphicsItemAnimation instances.
        # They are not kept anywhere, even if you invoke QTimeLine.start().
        self.timeline = QTimeLine(1000)
        self.timeline.setFrameRange(0, 100)
        self.timeline.frameChanged.connect(frame_move)
        self.timeline.finished.connect(timeline_ends)

        self.timeline.start()
示例#22
0
	def createAnimation(self):
		self.timeLine = QTimeLine(10*1000)
		self.timeLine.setFrameRange(0,60//(4/self.frameCount))
		self.timeLine.frameChanged.connect(self.refreshFrameIndex)
		self.timeLine.setLoopCount(0)
		self.timeLine.setCurveShape(3)
		self.timeLine.start()
示例#23
0
    def __init__(self):
        super(Widget, self).__init__()
        self.ui = Ui_SetupUsersWidget()
        self.ui.setupUi(self)

        self.edititemindex = None

        self.time_line = QTimeLine(400, self)
        self.time_line.setFrameRange(0, 220)
        self.time_line.frameChanged[int].connect(self.animate)

        self.ui.scrollArea.setFixedHeight(0)

        # User Icons
        self.normal_user_icon = QPixmap(":/gui/pics/users.png")
        self.super_user_icon = QPixmap(":/gui/pics/users.png")

        # Set disabled the create Button
        self.ui.createButton.setEnabled(False)

        # Connections
        self.ui.pass1.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.textChanged[str].connect(self.slotTextChanged)
        self.ui.username.textChanged[str].connect(self.slotTextChanged)
        self.ui.realname.textChanged[str].connect(self.slotTextChanged)
        self.ui.username.textEdited[str].connect(self.slotUserNameChanged)
        self.ui.realname.textEdited[str].connect(self.slotRealNameChanged)
        self.ui.userID.valueChanged[int].connect(self.slotTextChanged)
        self.ui.userIDCheck.stateChanged[int].connect(self.slotuserIDCheck)
        self.ui.createButton.clicked.connect(self.slotCreateUser)
        self.ui.cancelButton.clicked.connect(self.resetWidgets)
        self.ui.deleteButton.clicked.connect(self.slotDeleteUser)
        self.ui.editButton.clicked.connect(self.slotEditUser)
        self.ui.addMoreUsers.clicked.connect(self.slotAdvanced)
        self.ui.userList.itemDoubleClicked[QListWidgetItem].connect(self.slotEditUser)
        self.ui.pass2.returnPressed.connect(self.slotReturnPressed)

        # focusInEvent is not a signal
        # self.ui.pass1.focusInEvent[QFocusEvent].connect(self.checkCapsLock)
        # self.ui.pass2.focusInEvent[QFocusEvent].connect(self.checkCapsLock)
        # self.ui.username.focusInEvent[QFocusEvent].connect(self.checkCapsLock)
        # self.ui.realname.focusInEvent[QFocusEvent].connect(self.checkCapsLock)

        ctx.installData.users = []
        ctx.installData.autoLoginUser = None
        self.user_name_changed = False
        self.used_ids = []
    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()
示例#25
0
 def __init__(self,
              parent=None,
              hideWhileIdle=True,
              hidden=False,
              showFinished=3000):
     super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
     self._hideWhileIdle = hideWhileIdle
     self._hidden = hidden
     self._showFinished = showFinished
     self._timeline = QTimeLine(updateInterval=100,
                                frameChanged=self.setValue)
     self._timeline.setFrameRange(0, 100)
     self._hideTimer = QTimer(timeout=self._done,
                              singleShot=True,
                              interval=showFinished)
     if not hidden and not hideWhileIdle:
         self.show()
class FaderWidget(QLabel):

    """Custom Placeholder Fading Widget for tabs on TabWidget."""

    def __init__(self, parent):
        """Init class."""
        super(FaderWidget, self).__init__(parent)
        self.timeline, self.opacity, self.old_pic = QTimeLine(), 1.0, None
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(750)  # 500 ~ 750 Ms is Ok, Not more.

    def paintEvent(self, event):
        """Overloaded paintEvent to set opacity and pic."""
        painter = QPainter(self)
        painter.setOpacity(self.opacity)
        if self.old_pic:
            painter.drawPixmap(0, 0, self.old_pic)

    def animate(self, value):
        """Animation of Opacity."""
        self.opacity = 1.0 - value
        return self.hide() if self.opacity < 0.1 else self.repaint()

    def fade(self, old_pic, old_geometry, move_to):
        """Fade from previous tab to new tab."""
        if self.isVisible():
            self.close()
        if self.timeline.state():
            self.timeline.stop()
        self.setGeometry(old_geometry)
        self.move(1, move_to)
        self.old_pic = old_pic
        self.timeline.start()
        self.show()
示例#27
0
    def __init__(self, parent=None, wFlags=0):
        super(CustomProxy, self).__init__(parent, wFlags)

        self.popupShown = False
        self.currentPopup = None

        self.timeLine = QTimeLine(250, self)
        self.timeLine.valueChanged.connect(self.updateStep)
        self.timeLine.stateChanged.connect(self.stateChanged)
示例#28
0
    def __init__(self, parent, width=14, height=12, numofchannel=6):
        super(TSScene, self).__init__(parent)

        # set waveform windows
        figure = Figure()
        figure.set_size_inches(width, height)
        self.graphwidth = figure.dpi * width
        self.canvas = FigureCanvas(figure)
        self.addWidget(self.canvas)
        self.canvas.mpl_connect('button_press_event',self.button_press_event)
        self.canvas.mpl_connect('button_release_event', self.button_release_event)
        self.canvas.mpl_connect('motion_notify_event', self.motion_notify_event)
        self.canvas.mpl_connect('scroll_event', self.scroll_event)

        self.axesavailability = [True for i in range(numofchannel)]
        self.axes = []
        for i in range(numofchannel):
            self.axes.append(figure.add_subplot(str(numofchannel)+'1'+str(i+1)))


        # set backend data model
        self.data = TSData()
        self.visibleWave = {}
        self.starttime = None
        self.endtime = None

        # prepare for user input
        self.downxcoord = None
        self.wheelactive = False
        self.rect = None

        self.installEventFilter(self)
        self.showgap = False
        self.downbutton = None
        self.currentxdata = None

        self.count = 0
        self.state = 'ready'

        self.timeline = QTimeLine(1)
        self.timeline.setCurrentTime(0)
        self.timeline.setUpdateInterval(1)
        self.timeline.finished.connect(self.timeshift)
        self.timeline.finished.connect(self.animfinished)
    def __init__(self, *args, **kwargs):
        super(SideSlideDecorator, self).__init__(*args, **kwargs)

        self.resize(self.maximumSize())

        self.m_backgroundPixmap = QPixmap()

        self.m_slidePos = QPoint()
        self.m_timeline = QTimeLine()
        self.m_timeline.setDuration(260)
        self.m_timeline.setUpdateInterval(40)
        self.m_timeline.setEasingCurve(QEasingCurve.OutQuad)
        self.m_timeline.setStartFrame(0)
        self.m_timeline.setEndFrame(10000)

        self.m_decorationColor = QColor(0, 0, 0, 0)

        def frameChanged(_value):
            self.m_decorationColor = QColor(0, 0, 0, _value / 100)
            self.update()

        self.m_timeline.frameChanged.connect(frameChanged)
示例#30
0
    def openItem(self, item):
        if item == self.last_item:
            return

        if self.last_item:
            self.closeItem(self.last_item)

        self.animation = QTimeLine(ANIMATE_TIME, self)
        self.animation.setFrameRange(36, EXPANDED_SIZE)
        self.animation.frameChanged.connect(lambda x: item.setSizeHint(QSize(32, x)))
        self.animation.start()
        self.last_item = item
        self.animation.finished.connect(lambda: self.collectionList.setCurrentItem(item))
示例#31
0
    def __init__(self, old_widget, new_widget):
        QWidget.__init__(self, new_widget)
        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(300)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()
示例#32
0
class MyView(QGraphicsView):
    def __init__(self):
        super().__init__()

        self.initView()
        self.setupScene()
        self.setupAnimation()

        self.setGeometry(300, 150, 250, 250)

    def initView(self):

        self.setWindowTitle("Progress meter")
        self.setRenderHint(QPainter.Antialiasing)

        policy = Qt.ScrollBarAlwaysOff
        self.setVerticalScrollBarPolicy(policy)
        self.setHorizontalScrollBarPolicy(policy)

        self.setBackgroundBrush(self.palette().window())

        self.pm = ProgressMeter(self)
        self.pm.setPos(55, 55)

    def setupScene(self):

        self.scene = QGraphicsScene(self)
        self.scene.setSceneRect(0, 0, 250, 250)
        self.scene.addItem(self.pm)

        self.setScene(self.scene)

    def setupAnimation(self):

        self.timer = QTimeLine()
        self.timer.setLoopCount(0)
        self.timer.setFrameRange(0, 100)

        self.timer.frameChanged[int].connect(self.doStep)
        self.timer.start()

    def doStep(self, i):

        if not self.pm.increment():
            self.timer.stop()

        self.pm.update()
示例#33
0
class AnimationView(QWidget):
	"""docstring for AnimationView"""

	frameIndex = 0
	frameCount = 0

	def __init__(self, bmpFrames):
		super(AnimationView, self).__init__()
		self.setFixedSize(frameWidth,frameHeight)
		self.bmpSize =64
		if bmpFrames :
			self.bmpFrames = bmpFrames
			self.frameCount = len(bmpFrames)
			self.bmpSize = bmpFrames[0].width()
		else :
			self.initDefaultFrames()

	def initDefaultFrames(self):
		self.bmpFrames = []
		defaultImage = QImage("..\\resource\\default.bmp")
		imageWidth = defaultImage.width()
		imageHeight = defaultImage.height()
		#判断各幀图片是否是横向排列
		isHorizontal = min(imageWidth,imageHeight) == imageHeight
		#计算幀数
		self.frameCount = imageWidth//frameWidth if isHorizontal else imageHeight//frameHeight
		for i in range(0,self.frameCount):
			pixmap = QPixmap(defaultImage.copy(i*frameWidth if isHorizontal else 0,
				0 if isHorizontal else i*frameHeight,frameWidth,frameHeight))
			eliminateBackgroundColor(pixmap)
			self.bmpFrames.append(pixmap)
	
	def createAnimation(self):
		self.timeLine = QTimeLine(10*1000)
		self.timeLine.setFrameRange(0,60//(4/self.frameCount))
		self.timeLine.frameChanged.connect(self.refreshFrameIndex)
		self.timeLine.setLoopCount(0)
		self.timeLine.setCurveShape(3)
		self.timeLine.start()

	def refreshFrameIndex(self,currFrame):
		self.update()
		self.frameIndex = (self.frameIndex+1) % self.frameCount

	def paintEvent(self,event):
		painter = QPainter(self)
		painter.drawPixmap((frameWidth-self.bmpSize)//2,(frameHeight-self.bmpSize)//2,self.bmpFrames[self.frameIndex])
示例#34
0
class FaderWidget(QWidget):
    def __init__(self, old_widget, new_widget):

        QWidget.__init__(self, new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)

        self.pixmap_opacity = None
        self.timeline = QTimeLine(333, self)
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)

        self.resize(new_widget.size())
        self.show()

    def start(self, old_widget, new_widget):
        self.pixmap_opacity = 1.0
        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)

        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def animate(self, value):

        self.pixmap_opacity = 1.0 - value
        self.repaint()

    def paintEvent(self, event):
        if self.pixmap_opacity:
            QWidget.paintEvent(self, event)
            painter = QPainter(self)
            painter.setOpacity(self.pixmap_opacity)
            painter.drawPixmap(0, 0, self.old_pixmap)
示例#35
0
    def __init__(self, direction=DirectionDown, duration=300, parent=None):
        """
        Constructor
        
        @param direction direction of the animation
        @type int (one of DirectionDown or DirectionUp)
        @param duration duration of the animation
        @type int
        @param parent reference to the parent widget
        @type QWidget
        """
        super(E5AnimatedWidget, self).__init__(parent)

        self.__direction = direction
        self.__stepHeight = 0.0
        self.__stepY = 0.0
        self.__startY = 0
        self.__widget = QWidget(self)

        self.__timeline = QTimeLine(duration)
        self.__timeline.setFrameRange(0, 100)
        self.__timeline.frameChanged.connect(self.__animateFrame)

        self.setMaximumHeight(0)
示例#36
0
    def wheelEvent(self, event):
        numDegrees = event.angleDelta() / 8
        print("wheel: {}".format(numDegrees))
        numSteps = numDegrees.y() / 15
        self._numScheduledScalings += numSteps
        if self._numScheduledScalings * numSteps < 0:
            self._numScheduledScalings = numSteps

        anim = QTimeLine(350, self)
        anim.setUpdateInterval(20)
        anim.valueChanged.connect(self.ScalingTime)
        anim.finished.connect(self.AnimFinished)
        anim.start()
示例#37
0
 def wheelEvent(self, event):
     # Check if zooming is enabled
     if not self.parent.menu.options[1].isChecked(): return
     # Zooming event on mouse scroll
     numDegrees = event.angleDelta() / 8
     numSteps = (numDegrees / 15).y()
     self._numScheduledScalings += numSteps
     if self._numScheduledScalings * numSteps < 0:
         self._numScheduledScalings = numSteps
     anim = QTimeLine(350, self)
     anim.setUpdateInterval(20)
     anim.valueChanged.connect(self.scalingTime)
     anim.finished.connect(self.animFinished)
     anim.start()
示例#38
0
    def zoom(self, numDegrees):
        numSteps = numDegrees / 15
        self._numScheduledScalings += numSteps

        if (
                self._numScheduledScalings * numSteps < 0
        ):  # if user moved the wheel in another direction, we reset previously scheduled scalings
            self._numScheduledScalings = numSteps

        anim = QTimeLine(350, self)
        anim.setUpdateInterval(20)

        anim.valueChanged.connect(self.scalingTime)
        anim.finished.connect(self.scaleAnimFinished)
        anim.start()
示例#39
0
    def wheelEvent(self, event):
        numDegrees = event.angleDelta() / 8
        numSteps = numDegrees / 15
        self._numScheduledScalings += numSteps.y()
        """ if user moved the wheel in another direction, we reset previously scheduled scalings """
        if self._numScheduledScalings * numSteps.y() < 0:
            self._numScheduledScalings = numSteps.y()

        anim = QTimeLine(350, self)
        anim.setUpdateInterval(20)

        anim.valueChanged.connect(self.scalingTime)
        anim.finished.connect(self.animFinished)

        anim.start()
示例#40
0
    def createAndControl(self):
        newObject = 0
        className = self.theClassNames.at(self.theClassCombo.currentIndex())
        if (className == "QWidget"):
            newObject = QWidget()
        elif (className == "QPushButton"):
            newObject = QPushButton()
        elif (className == "QDialogButtonBox"):
            newObject = QDialogButtonBox()
        elif (className == "QTreeWidget"):
            newObject = QTreeWidget()
        elif (className == "QCalendarWidget"):
            newObject = QCalendarWidget()
        elif (className == "QAction"):
            newObject = QAction(None)
        elif (className == "QTimeLine"):
            newObject = QTimeLine()
        elif (className == "QTextDocument"):
            newObject = QTextDocument()

        if (not newObject):
            return

        newWidget = newObject
        if hasattr(newWidget, 'geometry'):
            r = newWidget.geometry()
            r.setSize(newWidget.sizeHint())
            r.setWidth(max(r.width(), 150))
            r.setHeight(max(r.height(), 50))
            r.moveCenter(QApplication.desktop().geometry().center())
            newWidget.setGeometry(r)
            newWidget.setWindowTitle(
                self.tr("Controlled Object: %s" % className))
            newWidget.show()

        if (self.theControlledObject):
            del self.theControlledObject

        self.theControlledObject = newObject
        self.theController.setObject(self.theControlledObject)
示例#41
0
    def translateVerticalEvent(self, dy):
        numSteps = dy * 20
        self._numScheduledVTranslations += numSteps

        if (
                self._numScheduledVTranslations * numSteps < 0
        ):  # if user moved the wheel in another direction, we reset previously scheduled scalings
            self._numScheduledVTranslations = numSteps

        if not self.animatingV:
            anim = QTimeLine(350, self)
            anim.setUpdateInterval(10)

            anim.valueChanged.connect(self.translateVTime)
            anim.finished.connect(self.translateVAnimFinished)
            anim.start()
示例#42
0
 def __init__(self, direction=DirectionDown, duration=300, parent=None):
     """
     Constructor
     
     @param direction direction of the animation
     @type int (one of DirectionDown or DirectionUp)
     @param duration duration of the animation
     @type int
     @param parent reference to the parent widget
     @type QWidget
     """
     super(E5AnimatedWidget, self).__init__(parent)
     
     self.__direction = direction
     self.__stepHeight = 0.0
     self.__stepY = 0.0
     self.__startY = 0
     self.__widget = QWidget(self)
     
     self.__timeline = QTimeLine(duration)
     self.__timeline.setFrameRange(0, 100)
     self.__timeline.frameChanged.connect(self.__animateFrame)
     
     self.setMaximumHeight(0)
示例#43
0
 def __init__(self, parent=None):
     super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
     self._timeline = QTimeLine(updateInterval=100, frameChanged=self.setValue)
     self._timeline.setFrameRange(0, 100)
     self._hideTimer = QTimer(timeout=self._done, singleShot=True, interval=3000)
示例#44
0
class TimedProgressBar(QProgressBar):
    """A QProgressBar showing a certain time elapse."""
    hideOnTimeout = True
    def __init__(self, parent=None):
        super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
        self._timeline = QTimeLine(updateInterval=100, frameChanged=self.setValue)
        self._timeline.setFrameRange(0, 100)
        self._hideTimer = QTimer(timeout=self._done, singleShot=True, interval=3000)

    def start(self, total, elapsed=0.0):
        """Starts showing progress.

        total is the number of seconds (maybe float) the timeline will last,
        elapsed (defaulting to 0) is the value to start with.

        """
        self._hideTimer.stop()
        self._timeline.stop()
        self._timeline.setDuration(total * 1000)
        self._timeline.setCurrentTime(elapsed * 1000)
        self.setValue(self._timeline.currentFrame())
        self._timeline.resume()
        if self.hideOnTimeout:
            self.show()

    def stop(self, showFinished=True):
        """Ends the progress display.

        If showFinished is True (the default), 100% is shown for a few
        seconds and then the progress is reset.
        The progressbar is hidden if the hideOnTimeout attribute is True.

        """
        self._hideTimer.stop()
        self._timeline.stop()
        if showFinished:
            self.setValue(100)
            self._hideTimer.start()
        else:
            self._done()

    def _done(self):
        if self.hideOnTimeout:
            self.hide()
        self.reset()
示例#45
0
class ExplorerNode(BaseNode):
    def __init__(self, nx_node, center_pos, nx_pos, steps, steps_max):
        """
        Create node in the graph scene

        :param tuple nx_node: Node info
        :param center_pos: The position of the center node
        :param nx_pos: Position of the nodes in the graph
        :param int steps: The steps from the center identity
        :param int steps_max: The steps max of the graph
        """
        super().__init__(nx_node, nx_pos)

        self.steps = steps
        self.steps_max = steps_max
        self.highlighted = False

        # text inside ellipse
        self.text_item = QGraphicsSimpleTextItem(self)
        self.text_item.setText(self.text)
        # center ellipse around text
        self.setRect(
            0,
            0,
            self.text_item.boundingRect().width() * 2,
            self.text_item.boundingRect().height() * 2
        )

        #  set anchor to the center
        self.setTransform(
            QTransform().translate(-self.boundingRect().width() / 2.0, -self.boundingRect().height() / 2.0))
        # center text in ellipse
        self.text_item.setPos(self.boundingRect().width() / 4.0, self.boundingRect().height() / 4.0)

        # cursor change on hover
        self.setAcceptHoverEvents(True)
        self.setZValue(1)

        # animation and moves
        self.timeline = None
        self.loading_timer = QTimer()
        self.loading_timer.timeout.connect(self.next_tick)
        self.loading_counter = 0
        self._refresh_colors()
        self.setPos(center_pos)
        self.move_to(nx_pos)

    def _refresh_colors(self):
        """
        Refresh elements in the node
        """
        # color around ellipse
        outline_color = QColor('black')
        outline_style = Qt.SolidLine
        outline_width = 1
        if self.status_wallet:
            outline_color = QColor('grey')
            outline_width = 2
        if not self.status_member:
            outline_color = QColor('red')
            outline_style = Qt.SolidLine
        self.setPen(QPen(outline_color, outline_width, outline_style))

        if self.highlighted:
            text_color = QColor('grey')
        else:
            text_color = QColor('black')

        if self.status_wallet == NodeStatus.HIGHLIGHTED:
            text_color = QColor('grey')
        self.text_item.setBrush(QBrush(text_color))

        # create gradient inside the ellipse
        gradient = QRadialGradient(QPointF(0, self.boundingRect().height() / 4), self.boundingRect().width())
        color = QColor()
        color.setHsv(120 - 60 / self.steps_max * self.steps,
                     180 + 50 / self.steps_max * self.steps,
                     60 + 170 / self.steps_max * self.steps)
        if self.highlighted:
            color = color.darker(200)
        color = color.lighter(math.fabs(math.sin(self.loading_counter / 100 * math.pi) * 100) + 100)
        gradient.setColorAt(0, color)
        gradient.setColorAt(1, color.darker(150))
        self.setBrush(QBrush(gradient))

    def move_to(self, nx_pos):
        """
        Move to corresponding position
        :param nx_pos:
        :return:
        """
        origin_x = self.x()
        origin_y = self.y()
        final_x = nx_pos[self.id][0]
        final_y = nx_pos[self.id][1]

        def frame_move(frame):
            value = self.timeline.valueForTime(self.timeline.currentTime())
            x = origin_x + (final_x - origin_x) * value
            y = origin_y + (final_y - origin_y) * value
            self.setPos(x, y)
            self.scene().node_moved.emit(self.id, x, y)

        def timeline_ends():
            self.setPos(final_x, final_y)
            self.timeline = None

        # Remember to hold the references to QTimeLine and QGraphicsItemAnimation instances.
        # They are not kept anywhere, even if you invoke QTimeLine.start().
        self.timeline = QTimeLine(1000)
        self.timeline.setFrameRange(0, 100)
        self.timeline.frameChanged.connect(frame_move)
        self.timeline.finished.connect(timeline_ends)

        self.timeline.start()

    def highlight(self):
        """
        Highlight the edge in the scene
        """
        self.highlighted = True
        self._refresh_colors()
        self.update(self.boundingRect())

    def neutralize(self):
        """
        Neutralize the edge in the scene
        """
        self.highlighted = False
        self._refresh_colors()
        self.update(self.boundingRect())

    def start_loading_animation(self):
        """
        Neutralize the edge in the scene
        """
        if not self.loading_timer.isActive():
            self.loading_timer.start(10)

    def stop_loading_animation(self):
        """
        Neutralize the edge in the scene
        """
        self.loading_timer.stop()
        self.loading_counter = 100
        self._refresh_colors()
        self.update(self.boundingRect())

    def next_tick(self):
        """
        Next tick
        :return:
        """
        self.loading_counter += 1
        self.loading_counter %= 100
        self._refresh_colors()
        self.update(self.boundingRect())
示例#46
0
 def closeItem(self, item):
     animation = QTimeLine(ANIMATE_TIME, self)
     animation.setFrameRange(146, CLOSED_SIZE)
     animation.frameChanged.connect(lambda x: item.setSizeHint(QSize(32, x)))
     animation.start()
示例#47
0
class QPageWidget(QScrollArea):
    """ The QPageWidget provides a stack widget with animated page transitions. """

    #Emits
    currentChanged = pyqtSignal()
    
    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
                
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        
        #qboxlayout setmargin özelliği yok
        #self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()

    def _animateFinished(self):
        """ Its called by TimeLine when animation finished.

        It first runs the outMethod of last Page and then the inMethod of current Page
        Finally tt gives the focus to the current page and fixes the scrollBar
        """

        # Disable other widgets
        for page in self.__pages:
            if not page == self.__pages[self.__current]:
                page.widget.setEnabled(False)

        # Run last page's outMethod if exists
        if self.__pages[self.__last].outMethod:
            self.__pages[self.__last].outMethod()

        # Run new page's inMethod if exists
        if self.__pages[self.__current].inMethod:
            self.__pages[self.__current].inMethod()

        # Give focus to the current Page
        self.__pages[self.__current].widget.setFocus()

        # Update scrollbar position for current page
        self.__scrollBar.setValue(self.__current * self.__base_value())

        # Emit currentChanged SIGNAL
        self.currentChanged.emit()

    def event(self, event):
        """ Overrides the main event handler to catch resize events """
        # Catch Resize event
        if event.type() == QEvent.Resize:
            # Update each page size limits to mainwidget's new size
            for page in self.__pages:
                page.widget.setMinimumSize(self.size())
                page.widget.setMaximumSize(self.size())

            # Update viewport size limits to mainwidget's new size
            # It's a workaround for QScrollArea updateGeometry bug
            self.viewport().setMinimumSize(self.size())
            self.viewport().setMaximumSize(self.size())

            # Update scrollbar position for current page
            self.__scrollBar.setValue(self.__current * self.__base_value())

        # Return the Event
        return QScrollArea.event(self, event)

    def keyPressEvent(self, event):
        """ Overrides the keyPressEvent to ignore them """
        pass

    def wheelEvent(self, event):
        """ Overrides the wheelEvent to ignore them """
        pass

    def createPage(self, widget, inMethod = None, outMethod = None):
        """ Creates and adds new Page for given widget with given in/out methods.

        widget: A QWidget which is the mainwidget for this Page
        inMethod: (optional) QPageWidget triggers this method when the Page appear
        outMethod: (optional) QPageWidget triggers this method when the Page disappear
        """
        self.addPage(Page(widget, inMethod, outMethod))

    def addPage(self, page):
        """ Adds the given Page to the stack.

        page: A Page object
        """
        # First remove the last page; its __tmp_page
        self.__pages.pop()

        # Add new page
        self.__pages.append(page)
        self.layout.addWidget(page.widget)

        # Add __tmp_page to end
        self.__pages.append(self.__tmp_page)
        self.layout.addWidget(self.__tmp_page.widget)

        # Create connections for page navigation signals from new page
        try:
            page.widget.pageNext.connect(self.next)
            page.widget.pagePrevious.connect(self.prev)
            page.widget.setCurrent[int].connect(self.setCurrent)
        except:
            pass

    def __setCurrent(self, pageNumber):
        """ Internal method to set current page index. """
        self.__last = self.__current
        self.__current = min(max(0, pageNumber), len(self.__pages) - 2)
        if pageNumber == len(self.__pages) - 1 and self.__return_to_first:
            self.__current = 0

    def setCurrent(self, pageNumber = 0):
        """ Set and flip the page with given pageNumber.

        pageNumber: index number of Page (default is 0)
        """
        self.__setCurrent(pageNumber)
        self.flipPage()

    def getCurrent(self):
        """ Returns current page index. """
        return self.__current

    def getCurrentWidget(self):
        """ Returns current page widget. """
        return self.getWidget(self.getCurrent())

    def getWidget(self, pageNumber):
        """ Returns widget for given page index 

        pageNumber: index number of Page
        """
        try:
            return self.__pages[pageNumber].widget
        except:
            return None

    def count(self):
        """ Returns number of pages. """
        return len(self.__pages) - 1

    def setAnimation(self, animation = 35):
        """ Set the transition animation with the given animation.

        animation: the number represents predefined QEasingCurves
                   List of predefined QEasingCurves can be found from:
                   http://doc.qt.nokia.com/4/qeasingcurve.html#Type-enum

                   Default is QEasingCurve::InOutBack (35)
        """
        self.__animation = animation
        self.__timeline.setEasingCurve(QEasingCurve(self.__animation))

    def setDuration(self, duration = 400):
        """ Set the transition duration.

        duration: duration time in ms
        """
        self.__duration = duration
        self.__timeline.setDuration(self.__duration)

    def flipPage(self, direction=0):
        """ Flip the page with given direction.

        direction: can be -1, 0 or +1
                   -1: previous page (if exists)
                    0: just flip to current page
                   +1: next page (if exists)
        """
        # Enable all widgets
        for page in self.__pages:
            page.widget.setEnabled(True)

        # Check given direction
        direction = direction if direction == 0 else max(min(1, direction), -1)

        # If direction is equal to zero no need to re-set current
        if not direction == 0:
            self.__setCurrent(self.__current + direction)

        # If last page is different from new page, flip it !
        if not self.__last == self.__current:
            self.__timeline.setFrameRange(self.__scrollBar.value(), self.__current * self.__base_value())
            self.__timeline.start()

    def next(self):
        """ Helper method to flip next page. """
        self.flipPage(1)

    def prev(self):
        """ Helper method to flip previous page. """
        self.flipPage(-1)
示例#48
0
class Widget(Ui_CollectionsWidget, QWidget, ScreenWidget):
    name = "collectionSelection"

    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.collections = None
        self.current_item = None
        self.last_item = None
        self.collectionList.itemClicked.connect(self.openItem)
        self.collectionList.currentItemChanged.connect(self.itemChanged)

    def fillCollections(self):
        self.collectionList.clear()
        selected = None
        for index, collection in enumerate(self.collections):
            self.addItem(collection)
            if ctx.installData.autoCollection  == collection:
                selected = index

        if not selected:
            selected = 0

        self.current_item = self.collectionList.item(selected)
        self.last_item = self.current_item
        self.collectionList.setCurrentRow(selected)

    def shown(self):
        self.collections = ctx.collections
        self.fillCollections()
        ctx.mainScreen.disableNext()
        if self.current_item:
            self.openItem(self.current_item)
        else:
            self.openItem(self.collectionList.item(0))
        self.check()

    def execute(self):
        ctx.installData.autoCollection = self.collectionList.itemWidget(self.current_item).collection
        return True

    def check(self):
        if self.current_item:
            ctx.mainScreen.enableNext()
        else:
            ctx.mainScreen.disableNext()

    def itemChanged(self, current, previous):
        self.current_item = current
        self.check()

    def addItem(self, collection):
        item = QListWidgetItem(self.collectionList)
        item.setSizeHint(QSize(36, CLOSED_SIZE))
        self.collectionList.addItem(item)
        self.collectionList.setItemWidget(item, CollectionItem(self, collection, item))

    def openItem(self, item):
        if item == self.last_item:
            return

        if self.last_item:
            self.closeItem(self.last_item)

        self.animation = QTimeLine(ANIMATE_TIME, self)
        self.animation.setFrameRange(36, EXPANDED_SIZE)
        self.animation.frameChanged.connect(lambda x: item.setSizeHint(QSize(32, x)))
        self.animation.start()
        self.last_item = item
        self.animation.finished.connect(lambda: self.collectionList.setCurrentItem(item))

    def closeItem(self, item):
        animation = QTimeLine(ANIMATE_TIME, self)
        animation.setFrameRange(146, CLOSED_SIZE)
        animation.frameChanged.connect(lambda x: item.setSizeHint(QSize(32, x)))
        animation.start()
示例#49
0
class E5AnimatedWidget(QWidget):
    """
    Class implementing an animated widget.
    """
    DirectionDown = 0
    DirectionUp = 1
    
    def __init__(self, direction=DirectionDown, duration=300, parent=None):
        """
        Constructor
        
        @param direction direction of the animation
        @type int (one of DirectionDown or DirectionUp)
        @param duration duration of the animation
        @type int
        @param parent reference to the parent widget
        @type QWidget
        """
        super(E5AnimatedWidget, self).__init__(parent)
        
        self.__direction = direction
        self.__stepHeight = 0.0
        self.__stepY = 0.0
        self.__startY = 0
        self.__widget = QWidget(self)
        
        self.__timeline = QTimeLine(duration)
        self.__timeline.setFrameRange(0, 100)
        self.__timeline.frameChanged.connect(self.__animateFrame)
        
        self.setMaximumHeight(0)
    
    def widget(self):
        """
        Public method to get a reference to the animated widget.
        
        @return reference to the animated widget
        @rtype QWidget
        """
        return self.__widget
    
    @pyqtSlot()
    def startAnimation(self):
        """
        Public slot to start the animation.
        """
        if self.__timeline.state() == QTimeLine.Running:
            return
        
        shown = 0
        hidden = 0
        
        if self.__direction == self.DirectionDown:
            shown = 0
            hidden = -self.__widget.height()
        
        self.__widget.move(QPoint(self.__widget.pos().x(), hidden))
        
        self.__stepY = (hidden - shown) / 100.0
        self.__startY = hidden
        self.__stepHeight = self.__widget.height() / 100.0
        
        self.__timeline.setDirection(QTimeLine.Forward)
        self.__timeline.start()
    
    @pyqtSlot(int)
    def __animateFrame(self, frame):
        """
        Private slot to animate the next frame.
        
        @param frame frame number
        @type int
        """
        self.setFixedHeight(frame * self.__stepHeight)
        self.__widget.move(self.pos().x(),
                           self.__startY - frame * self.__stepY)
    
    @pyqtSlot()
    def hide(self):
        """
        Public slot to hide the animated widget.
        """
        if self.__timeline.state() == QTimeLine.Running:
            return
        
        self.__timeline.setDirection(QTimeLine.Backward)
        self.__timeline.finished.connect(self.close)
        self.__timeline.start()
        
        p = self.parentWidget()
        if p is not None:
            p.setFocus()
    
    def resizeEvent(self, evt):
        """
        Protected method to handle a resize event.
        
        @param evt reference to the event object
        @type QResizeEvent
        """
        if evt.size().width() != self.__widget.width():
            self.__widget.resize(evt.size().width(), self.__widget.height())
        
        super(E5AnimatedWidget, self).resizeEvent(evt)
示例#50
0
class CustomProxy(QGraphicsProxyWidget):
    def __init__(self, parent=None, wFlags=0):
        super(CustomProxy, self).__init__(parent, wFlags)

        self.popupShown = False
        self.currentPopup = None

        self.timeLine = QTimeLine(250, self)
        self.timeLine.valueChanged.connect(self.updateStep)
        self.timeLine.stateChanged.connect(self.stateChanged)

    def boundingRect(self):
        return QGraphicsProxyWidget.boundingRect(self).adjusted(0, 0, 10, 10)

    def paintWindowFrame(self, painter, option, widget):
        color = QColor(0, 0, 0, 64)

        r = self.windowFrameRect()
        right = QRectF(r.right(), r.top()+10, 10, r.height()-10)
        bottom = QRectF(r.left()+10, r.bottom(), r.width(), 10)
        intersectsRight = right.intersects(option.exposedRect)
        intersectsBottom = bottom.intersects(option.exposedRect)
        if intersectsRight and intersectsBottom:
            path = QPainterPath()
            path.addRect(right)
            path.addRect(bottom)
            painter.setPen(Qt.NoPen)
            painter.setBrush(color)
            painter.drawPath(path)
        elif intersectsBottom:
            painter.fillRect(bottom, color)
        elif intersectsRight:
            painter.fillRect(right, color)

        super(CustomProxy, self).paintWindowFrame(painter, option, widget)

    def hoverEnterEvent(self, event):
        super(CustomProxy, self).hoverEnterEvent(event)

        self.scene().setActiveWindow(self)
        if self.timeLine.currentValue != 1:
            self.zoomIn()

    def hoverLeaveEvent(self, event):
        super(CustomProxy, self).hoverLeaveEvent(event)

        if not self.popupShown and (self.timeLine.direction() != QTimeLine.Backward or self.timeLine.currentValue() != 0):
            self.zoomOut()

    def sceneEventFilter(self, watched, event):
        if watched.isWindow() and (event.type() == QEvent.UngrabMouse or event.type() == QEvent.GrabMouse):
            self.popupShown = watched.isVisible()
            if not self.popupShown and not self.isUnderMouse():
                self.zoomOut()

        return super(CustomProxy, self).sceneEventFilter(watched, event)

    def itemChange(self, change, value):
        if change == self.ItemChildAddedChange or change == self.ItemChildRemovedChange :
            if change == self.ItemChildAddedChange:
                self.currentPopup = value
                self.currentPopup.setCacheMode(self.ItemCoordinateCache)
                if self.scene() is not None:
                    self.currentPopup.installSceneEventFilter(self)
            elif self.scene() is not None:
                self.currentPopup.removeSceneEventFilter(self)
                self.currentPopup = None
        elif self.currentPopup is not None and change == self.ItemSceneHasChanged:
                self.currentPopup.installSceneEventFilter(self)

        return super(CustomProxy, self).itemChange(change, value)

    def updateStep(self, step):
        r = self.boundingRect()
        self.setTransform(QTransform() \
                            .translate(r.width() / 2, r.height() / 2)\
                            .rotate(step * 30, Qt.XAxis)\
                            .rotate(step * 10, Qt.YAxis)\
                            .rotate(step * 5, Qt.ZAxis)\
                            .scale(1 + 1.5 * step, 1 + 1.5 * step)\
                            .translate(-r.width() / 2, -r.height() / 2))

    def stateChanged(self, state):
        if state == QTimeLine.Running:
            if self.timeLine.direction() == QTimeLine.Forward:
                self.setCacheMode(self.NoCache)
        elif state == QTimeLine.NotRunning:
            if self.timeLine.direction() == QTimeLine.Backward:
                self.setCacheMode(self.DeviceCoordinateCache)

    def zoomIn(self):
        if self.timeLine.direction() != QTimeLine.Forward:
            self.timeLine.setDirection(QTimeLine.Forward)
        if self.timeLine.state() == QTimeLine.NotRunning:
            self.timeLine.start()

    def zoomOut(self):
        if self.timeLine.direction() != QTimeLine.Backward:
            self.timeLine.setDirection(QTimeLine.Backward)
        if self.timeLine.state() == QTimeLine.NotRunning:
            self.timeLine.start()