Example #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()
Example #2
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()
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()
Example #4
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()
Example #5
0
class CCountUp(QLabel):
    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)

    def pause(self):
        """暂停
        """
        self.timeline.setPaused(True)

    def resume(self):
        """继续
        """
        self.timeline.resume()

    def isPaused(self):
        """是否暂停
        """
        return self.timeline.state() == QTimeLine.Paused

    def reset(self):
        """重置
        """
        self.timeline.stop()
        self.isFloat = False  # 是否是小数
        self.setText('0')

    def onFrameChanged(self, value):
        if self.isFloat:
            value = round(value / 100.0 + 0.00001, 2)
        value = str(format(value, ','))
        self.setText(value + '0' if value.endswith('.0') else value)

    def setDuration(self, duration):
        """设置动画持续时间
        :param duration:
        """
        self.timeline.setDuration(duration)

    def setNum(self, number):
        """设置数字
        :param number:        int or float
        """
        if isinstance(number, int):
            self.isFloat = False
            self.timeline.setFrameRange(0, number)
        elif isinstance(number, float):
            self.isFloat = True
            self.timeline.setFrameRange(0, number * 100)
        self.timeline.stop()
        self.setText('0')
        self.timeline.start()
Example #6
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
Example #7
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
Example #8
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()
Example #9
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()
class MainWindow(QMainWindow):
    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

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            app.closeAllWindows()
class SideSlideDecorator(QWidget):
    m_slidePos: QPoint
    m_slideWidgetPixmap: QPixmap
    m_timeline: QTimeLine
    m_backgroundPixmap: QPixmap
    m_decorationColor: QColor

    clicked = pyqtSignal()

    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)

    def grabSlideWidget(self, _slideWidget):
        self.m_slideWidgetPixmap = _slideWidget.grab()

    def grabParent(self):
        # self.m_backgroundPixmap = self.parentWidget().grab()
        pass

    def decorate(self, _dark):
        if self.m_timeline.state() == QTimeLine.Running:
            self.m_timeline.stop()

        self.m_timeline.setDirection(
            QTimeLine.Forward if _dark else QTimeLine.Backward)
        self.m_timeline.start()

    def slidePos(self):
        return self.m_slidePos

    def setSlidePos(self, _pos):
        if self.m_slidePos != _pos:
            self.m_slidePos = _pos
            self.update()

    def paintEvent(self, _event):
        painter = QPainter(self)
        painter.drawPixmap(0, 0, self.m_backgroundPixmap)
        painter.fillRect(self.rect(), self.m_decorationColor)
        painter.drawPixmap(self.m_slidePos, self.m_slideWidgetPixmap)

        super(SideSlideDecorator, self).paintEvent(_event)

    def mousePressEvent(self, _event):
        self.clicked.emit()

        super(SideSlideDecorator, self).mousePressEvent(_event)

    _slidePos = pyqtProperty(QPoint, fget=slidePos, fset=setSlidePos)
Example #12
0
class QTreeWidget(CoreQTreeWidget):

    def __init__(self, tableWidget, icons, showHidden):

        super(QTreeWidget, self).__init__(tableWidget, icons, showHidden)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.setAcceptDrops(True)
        self.dragModSoon = False  # dragMod just starts after 0.1 sec
        self.started = 0  # to take the time of dragModSoon

        self.dragSource = None
        self.dragMod = False
        self.copyDrag = False
        self.lastp = QtCore.QPoint(0, 0)  # Last position of the dragged item

        # USED FOR PREVIEW #

        # idx of a temporary moved/inserted item (not Voiditem)
        self.callback = None
        # Used for the drag and drop preview
        self.stillInItem = None
        self.voididxlist = []

        # SIZES(some handeld automatically) #

        self.circleSize = 1.5/2.  # Scaling factor for the nodes
        self.rw = 0
        self.rh = 0
        self.minr = 0

        # ANIMATION HELP #

        self.lineList_old = []
        self.lineList_new = []

        self.nodeCopy = []  # dictionarys filled with information

        self.old_opacity = 1
        self.timeline = None
        self.animationDuration = 200
        self.needUpdate = False

    def getItemList(self):
        """Returns a list of the items (Depth-first search [preordering])"""
        itemlist = []
        self.rekursivHelp(self.topLevelItem(0), itemlist)
        return itemlist

    def rekursivHelp(self, item, list):
        """Recursive help for the getItemList method"""
        list.append(item)
        for i in range(item.childCount()):
            self.rekursivHelp(item.child(i), list)

    def tableChanged(self):
        super(QTreeWidget, self).tableChanged()
        self.needUpdate = True

    def paintEvent(self, event):
        """Painting the view, if there is a root item"""

        if self.itemAt(0, 0) is None:
            return

        painter = QPainter(self.viewport())

        self.makeImage(painter)

        # drawing the dragged item
        if (self.dragMod and self.dragSource == self.source and
                self.currentItem() is not None):
            pos = self.lastp - QtCore.QPoint(self.minr/4, self.minr/4)
            self.paintItem(self.currentItem(), pos,
                           painter, self.xml)
            if self.timeline is None:
                # paintItem saves the drawn node. But the dragged Node is not
                # fixed thats why I remove it again.
                del self.nodeCopy[-1]

        painter.end()

    def makeImage(self, painter):
        """
        This method draws the image to a given painter.
        The algorithm works like this:

        - Find out how the items have to be placed, relativly
        - Take the relativ height and width of the tree
        - Now, set the position with absolute values
        - Save the lines
        - Check if some transitions have to be made:
            - if there is no transition required at the moment
            - and the lines changed or needUpdate flag is set

        For the tranistion take a look at the methods
        'animate' and 'animationEnd'.
        """

        painter.setRenderHint(QPainter.TextAntialiasing, True)
        painter.setRenderHint(QPainter.Antialiasing, True)

        itemList = self.getItemList()

        wDSF = 1  # width Dependend Scaling Factor
        hDSF = 1  # height Dependend Scaling Factor

        width = self.width()
        height = self.height()

        # The depth of the Tree
        maxlevel = 4
        # Max width in a Tree level
        maxlevelwidth = 1

        # Setting up maxlevel & item.level values
        for item in itemList:
            item.pos = QtCore.QPoint(0, 0)
            if item.parent() is not None:
                if item.getType() not in ['PULSE']:
                    item.level = item.parent().level+1
                    if item.level > maxlevel:
                        maxlevel = item.level

        # List of the width in a tree level
        levelwidth = [0] * len(itemList)

        for item in itemList:
            if item.parent() is not None:
                # This way, we dont write a node over the child of another node
                for j in range(item.level, len(levelwidth)):
                    if levelwidth[item.level] < levelwidth[j]:
                        levelwidth[item.level] = levelwidth[j]
                # Setting up the Item position
                item.pos = QtCore.QPoint(levelwidth[item.level], item.level)

                # A child cant be on the left side of a parent node
                if item.pos.x() < item.parent().pos.x():
                    item.pos = QtCore.QPoint(item.parent().pos.x(),
                                             item.pos.y())
                    levelwidth[item.level] = item.pos.x()

                # PULSE nodes don't grow to the side
                if item.getType() not in ['PULSE']:
                    levelwidth[item.level] += 1

                # To handle multiply PULSE nodes, we take their parent node
                if item.getType() in ['ATOMICSEQUENCE']:
                    if item.childCount() != 0:
                        # Multiple PULSE nodes takes 1 width in a tree level
                        levelwidth[item.level+1] += 1
                    # Multiple PULES nodes increasing the tree depth
                    if (item.level + item.childCount()) > maxlevel:
                        maxlevel = (item.level + item.childCount())

        # Getting the maxlevelwidth
        maxlevelwidth = max(levelwidth)

        if maxlevelwidth == 0:
            maxlevelwidth = 1

        self.rw = width/(maxlevelwidth) * wDSF
        self.rh = height/(maxlevel+1) * hDSF  # +1 is needed, to make it fit

        self.minr = self.rw if self.rw < self.rh else self.rh

        # ------------------------------------------------------------------- #
        # Positioning #
        # ------------------------------------------------------------------- #

        for item in itemList:
            if item.getType() not in ['PULSE']:
                qpoint = QtCore.QPoint(self.minr/6 + 3, 3)
                item.pos = QtCore.QPoint(item.pos.x()*self.rw,
                                         item.pos.y()*self.rh) + qpoint
                if item.getType() in ['ATOMICSEQUENCE']:
                    for i in range(item.childCount()):
                        child = item.child(i)
                        child.pos = QtCore.QPoint(
                                item.pos.x(), item.pos.y() +
                                (i+1)*self.minr*self.circleSize)

        # ------------------------------------------------------------------- #
        # Save Lines #
        # ------------------------------------------------------------------- #

        painter.linePainter(item)

        self.lineList_new = [[]]
        for item in itemList:
            # No lines between ATOMIC... and PULSE
            if item.getType() not in ['ATOMICSEQUENCE', 'COILARRAY']:
                for i in range(item.childCount()):
                    if not item.child(i).visible:
                        continue
                    self.lineList_new += [[
                            item.pos +
                            QtCore.QPoint(self.minr*self.circleSize/2,
                                          self.minr*self.circleSize/2),
                            item.child(i).pos +
                            QtCore.QPoint(self.minr*self.circleSize/2,
                                          self.minr*self.circleSize/2)]]

        # ------------------------------------------------------------------- #
        # possible Animation start #
        # ------------------------------------------------------------------- #

        if (self.timeline is None and
                (self.lineList_new[:] != self.lineList_old[:] or
                 self.needUpdate)):
            self.needUpdate = False
            self.timeline = QTimeLine()
            self.timeline.valueChanged.connect(self.animate)
            self.timeline.finished.connect(self.animationEnd)
            self.timeline.setDuration(self.animationDuration)
            self.timeline.start()

        # ------------------------------------------------------------------- #
        # Drawing Lines #
        # ------------------------------------------------------------------- #

        painter.setOpacity(self.old_opacity)
        for line in self.lineList_old:
            if line != []:
                painter.drawLine(line[0], line[1])

        if self.old_opacity != 1:       # with Animation
            painter.setOpacity(1-self.old_opacity)
            for line in self.lineList_new:
                if line != []:
                    painter.drawLine(line[0], line[1])

        # ------------------------------------------------------------------- #
        # Drawing Nodes #
        # ------------------------------------------------------------------- #

        painter.setOpacity(1)
        if self.timeline is None:       # without Animation
            if len(self.nodeCopy) == 0:
                tmp = copy.deepcopy(self.xml)
                for item in itemList:     # drawing and saving new nodes
                    if item is not None and item.visible:
                        self.paintItem(item, item.pos, painter, tmp)
            else:
                for cp in self.nodeCopy:  # using old nodes for drawing
                    self.paintItem2(cp, painter)

        else:                           # with Animation
            painter.setOpacity(self.old_opacity)
            for cp in self.nodeCopy:
                self.paintItem2(cp, painter)
            painter.setOpacity(1-self.old_opacity)
            for item in itemList:
                if item is not None and item.visible:
                    self.paintItem(item, item.pos, painter, self.xml)

    def animationEnd(self):
        """
        AnimationEnd cleans up the animation. Called by QTimeLine.
        """
        self.lineList_old = self.lineList_new
        self.lineList_new = None
        self.old_opacity = 1.0
        self.nodeCopy = []      # removing old nodes
        self.timeline = None
        self.updateImage()

    def animate(self, value):
        """
        Animate makes a little change for the tranistion. Called by QTimeLine.
        """
        self.old_opacity = 1.0 - value
        self.updateImage()

    def calcVoidItems(self):
        """
        This method creates the Voiditems for the preview.
        """
        if not self.dragMod:
            return

        # ------------------------------------------------------------------- #
        # Calculating VoidItems indexes #
        # ------------------------------------------------------------------- #

        self.voididxlist = []
        for item in self.getItemList():
            if item.getType() not in ['PULSE']:
                idx = item.idx() + [item.childCount()]
                if self.checkVoidItem(idx):
                    self.voididxlist += [idx]

        dragIndex = None
        if self.currentItem() is not None:  # saving the current item idx
            dragIndex = self.currentItem().idx()

        # ------------------------------------------------------------------- #
        # Creation of Voiditems #
        # ------------------------------------------------------------------- #

        for voididx in self.voididxlist:
            if self.dragSource == self.source:  # not using button drag
                if self.callback is not None:       # item not moved/copyd
                    self.setCurrentItem(self.getItem(self.callback))
#
                    self.itemCopy.emit()
                    self.itemMoved.emit(self.callback, voididx)
                else:                               # item moved/copyd
                    if voididx is self.voididxlist[0]:
                        dragIndex[-1] += 1
                        self.itemCopy.emit()
                        self.itemMoved.emit(dragIndex, voididx)
                        dragIndex[-1] -= 1
                        self.setCurrentItem(self.getItem(dragIndex))
                    else:
                        self.setCurrentItem(self.getItem(self.voididxlist[0]))
                        self.itemCopy.emit()
                        self.itemMoved.emit(self.voididxlist[0], voididx)
            else:                                # using button drag
                if self.callback is None:       # item not inserted
                    if voididx is self.voididxlist[0]:
                        self.insertItem(voididx)
                    else:
                        self.setCurrentItem(self.getItem(self.voididxlist[0]))
                        self.itemCopy.emit()
                        self.itemMoved.emit(self.voididxlist[0], voididx)
                else:                           # item already inserted
                    self.setCurrentItem(self.getItem(self.callback))
                    self.itemCopy.emit()
                    self.itemMoved.emit(self.callback, voididx)

        if dragIndex is not None:       # setting the current item back
            self.setCurrentItem(self.getItem(dragIndex))

        self.markVoidItems()    # finishing void items

    def checkVoidItem(self, idx):
        """
        Checks, if an idx can be taken for a new VoidItem. First some special
        cases are caught and then the standard checkDrop function is used.
        """

        if self.callback is not None:
            if len(idx) == len(self.callback):
                numb = len(self.callback)-1
                if (idx[0:numb] == self.callback[0:numb] and
                        idx[numb] >= self.callback[numb]):
                    return False
            else:
                if len(idx) >= len(self.callback):
                    numb = len(self.callback)
                    if idx[0:numb] == self.callback[0:numb]:
                        return False
        return self.checkDrop(idx)

    def setBranchVoid(self, root, isVoid):
        """
        This Method sets the isVoid flag of a hole branch to the given
        boolean value in 'isVoid'.
        """

        change = [root]
        for node in change:
            node.isVoid = isVoid
            for i in range(node.childCount()):
                change += [node.child(i)]

    def checkDrop(self, dropidx):
        """
        This Methods checks, if a (copy)move/insertion of an item is
        legal.
        """

        dropIndex = dropidx[:]
        tmp = copy.deepcopy(self.xml)
        if self.dragSource == self.source:
            dragIndex = self.currentItem().idx()
            if self.copyDrag:
                tmp.copy(dragIndex)
                dragIndex[-1] += 1
            else:
                if len(dropIndex) >= len(dragIndex):
                    numb = len(dragIndex)
                    if dragIndex[0:numb] <= dropIndex[0:numb]:
                        if dropIndex[0:numb] == dragIndex[0:numb]:
                            return False
                        dropIndex[numb-1] -= 1
            try:
                tmp._move(dragIndex, dropIndex)
                status, msg = tmp.checkCommand(dropIndex)
                if msg is not None:
                    return False
            # exception caused, when tmp.checkCommand wont return 2 values
            except:
                return False
        else:
            tag = self.dragSource.text()
            idx = dropIndex[0:-1]

            if len(idx) == 0:
                return False

            tmp = copy.deepcopy(self.xml)
            msg = tmp._insert(idx, tag)
            if msg is not None:
                return False
        return True

    def deleteVoidItems(self):
        """
        Removs all Items, which are VoidItems.
        """

        savedidx = None
        if self.currentItem() is not None:
            savedidx = self.currentItem().idx()
        for idx in self.voididxlist:
            self.setCurrentItem(self.getItem(idx))
            self.treeItemDelete()
        if savedidx is not None:
            self.setCurrentItem(self.getItem(savedidx))
        self.voididxlist = []

    def paintItem(self, item, pos, painter, xml):
        """
        This method is a preparation for the item painting in 'paintItem2'.
        The infomation, which is required to draw an item, is saved if
        needed (for the animation).
        """

        informlist = {
                "pos": pos, "text": item.getName(),
                "backgroundColor": item.background(0).color(),
                "isVoid": item.isVoid,
                "type": item.getType(),
                "iscurrent": item is self.currentItem(),
                "idx": item.idx(),
                "xml": xml,
                "textcolor": item.foreground(0).color(),
                "font": item.font(0),
                "minr": self.minr}

        if self.timeline is None:
            self.nodeCopy.append(informlist)

        self.paintItem2(informlist, painter)

    def paintItem2(self, itemInfos, painter):
        """
        In this method, the items are painted. The attribute 'iteminfos'
        should contain a dictionary with the needed informtion.
        """

        minSizeForPulsPic = 25

        sIC = QtGui.QColor(0, 150, 200)  # selected item color

        sICBW = 2  # selected item color border width

        minr = itemInfos["minr"]

        # ------------------------------------------------------------------- #
        # Draw Form #
        # ------------------------------------------------------------------- #

        # drawshape = needed shape
        # rect = Postion + size of the shape

        if itemInfos["type"] in ['PULSE', 'COIL']:
            rect = QtCore.QRect(itemInfos["pos"].x()-minr/6,
                                itemInfos["pos"].y(),
                                minr*self.circleSize + self.minr/3,
                                minr*self.circleSize)
            drawshape = painter.drawRect
        else:
            rect = QtCore.QRect(itemInfos["pos"].x(), itemInfos["pos"].y(),
                                minr*self.circleSize,
                                minr*self.circleSize)
            drawshape = painter.drawEllipse

        # shape color
        colorB = itemInfos["backgroundColor"]
        if self.callback is not None:
            if ((self.dragSource == self.source and
                 itemInfos["idx"] == self.callback and
                 not itemInfos["iscurrent"]) or
                (self.dragSource != self.source and
                 itemInfos["iscurrent"])):
                colorB = QtGui.QColor(220, 220, 220)

        # alphaf(1) to overdraw the lines, which connects the nodes
        # TODO:
        colorB.setAlphaF(1)
        if itemInfos["iscurrent"]:  # draw a blue border for the currentItem
            painter.setBrush(sIC)
            drawshape(QtCore.QRect(rect.x() - sICBW,
                                   rect.y() - sICBW,
                                   rect.width() + 2*sICBW,
                                   rect.height() + 2*sICBW))

        if itemInfos["isVoid"]:     # VoidItems are drawn with orange
            colorB = QtGui.QColor('orange')
            painter.formPainter(rect, None, colorB, itemtype=itemInfos["type"])
        else:
            painter.formPainter(rect, None, colorB, itemtype=itemInfos["type"])

        drawshape(rect)  # Drawing the shape

        # ------------------------------------------------------------------- #
        # Draw Icon #
        # ------------------------------------------------------------------- #

        painter.iconPainter()
        icon = None

        if minr >= minSizeForPulsPic:
            xitem = itemInfos["xml"].read(itemInfos["idx"])
            if xitem.get('type') in ['PULSE', 'COIL']:
                icon = self.icons[xitem.tag]

                painter.drawPixmap(
                        itemInfos["pos"] + QtCore.QPoint(0, minr * 1/7),
                        icon, QtCore.QRect(0, 0, icon.width(), icon.height()))

        # ------------------------------------------------------------------- #
        # Draw Text #
        # ------------------------------------------------------------------- #

        painter.textPainter(textColor=itemInfos["textcolor"],
                            font=itemInfos["font"])

        if icon is not None:
            painter.drawText(itemInfos["pos"] + QtCore.QPoint(
                    icon.width(), icon.height() + minr*1/7), itemInfos["text"])
        else:
            painter.drawText(QtCore.QRectF(rect), QtCore.Qt.AlignCenter,
                             itemInfos["text"])

    def pointInItem(self, p, item):
        """
        Checks if a point is in the shape of an Item. This is used to
        detect, if a user clicks or hovers over an item (possible drop
        action).
        """

        m = self.minr
        if item.getType() in ['PULSE']:     # Checks if p is in a Rectangle
            return (p.x() > item.pos.x()-m/6 and
                    p.y() > item.pos.y() and
                    p.x() < item.pos.x()-m/6-2+m*self.circleSize+m/3 and
                    p.y() < item.pos.y()+m*self.circleSize)
        else:                               # Checks if p is in a Circle
            return (math.sqrt((p.x()-item.pos.x()-m*self.circleSize/2)**2 +
                              (p.y()-item.pos.y()-m*self.circleSize/2)**2) <
                    m*self.circleSize/2)

    def mousePressEvent(self, e):
        self.lastp = e.pos()
        for item in self.getItemList():
            if self.pointInItem(self.lastp, item):
                self.setCurrentItem(item)
                self.treeItemClicked()
                self.dragModSoon = True
                self.started = time.time()
                self.nodeCopy = []
                self.updateImage()
                break

    def mouseReleaseEvent(self, e):
        self.lastp = e.pos()

        if self.dragMod:
            dropevent = QtGui.QDropEvent(e.pos(), QtCore.Qt.DropAction(),
                                         QtCore.QMimeData(),
                                         QtCore.Qt.MouseButton(),
                                         QtCore.Qt.KeyboardModifiers(),
                                         QtCore.QEvent.Drop)
            dropevent.source = self.source
            if self.callback is not None and self.callback in self.voididxlist:
                self.voididxlist.remove(self.callback)
            self.deleteVoidItems()

            if self.callback is not None:
                if self.dragSource == self.source and not self.copyDrag:
                    self.treeItemDelete()
            self.callback = None
            self.dragMod = False
            self.needUpdate = True
            self.updateImage()
        self.dragModSoon = False

    def mouseMoveEvent(self, event):
        e = QtGui.QMouseEvent(event)
        self.lastp = e.pos()

        if self.dragModSoon and not self.dragMod:
            if time.time() - self.started > 0.1:
                self.dragMod = True
                self.dragSource = self.source
                self.calcVoidItems()

        if self.dragMod:
            self.previewManager(event)
            self.updateImage()

    def stillInItemFunc(self, p):
        """
        This Method detects, if the cursor is still hovering over the
        shape, which causes a change. By making a move/copy/insert preview,
        it is possible, that the new shapes don't matches the cursor
        position, so that a preview would be volatile without this method.
        """

        m = self.stillInItem[2]
        itempos = self.stillInItem[1]

        if self.stillInItem[0] in ['PULSE']:    # p in Rectangle
            return (p.x() > itempos.x()-m/6 and
                    p.y() > itempos.y() and
                    p.x() < itempos.x()-m/6-2+m*self.circleSize+m/3 and
                    p.y() < itempos.y()+m*self.circleSize)
        else:                                   # p in Circle
            return (math.sqrt((p.x()-itempos.x()-m*self.circleSize/2)**2 +
                              (p.y()-itempos.y()-m*self.circleSize/2)**2) <
                    m*self.circleSize/2)

    def setBranchVisible(self, item, visible):
        """
        Changes the visibility of a complete branch. The given item should be
        the root of the branch. This method is used in the move preview
        (without copy).
        """

        change = [item]
        for node in change:
            node.visible = visible
            for i in range(node.childCount()):
                change += [node.child(i)]

    def previewManager(self, event):
        """
        This method decides, if a (copy)move/insert preview has to be done.
        It can also delete a preview, if the dragged item is not over a shape
        anymore.
        """

        # Limiting the the calls of this method
        if time.time() - self.started > 0.1:
            self.started = time.time()

            dropIndex = self.calcDropIndex(event.pos())
            if dropIndex is not None:               # Cursor over shape
                if self.callback is None:           # There is no preview
                    self.makePreview(event, dropIndex)  # make move/copy/insert
            elif (self.callback is not None and
                  not self.stillInItemFunc(event.pos())):
                self.deletePreview()            # undo move/copy/insert
                self.stillInItem = None

    def deletePreview(self):
        """
        This method deletes a preview, that is caused by dragging an item over
        another item.
        """

        self.deleteVoidItems()
        if self.dragSource == self.source:      # not caused by a button drag
            item = self.getItem(self.callback)
            self.setCurrentItem(item)
            self.treeItemDelete()
            self.callback = None
            self.setCurrentItem(self.getItem(self.copyhelp))
            if not self.copyDrag:
                self.currentItem().visible = True
        else:                                   # caused by a button drag
            self.setCurrentItem(self.getItem(self.callback))
            self.treeItemDelete()
            self.callback = None
        self.calcVoidItems()
        self.needUpdate = True

    def makePreview(self, event, dropIndex):
        """
        Checks and creates a new (copy)move/insert preview.
        """

        if not self.checkDrop(dropIndex):   # We can't drop the Item here
            return

        if self.dragSource == self.source:  # not caused by a button
            self.makePreviewCopyDrag(event, dropIndex)  # (copy)move
        else:                               # caused by a button
            self.makePreviewInsert(event, dropIndex)    # insert
        self.needUpdate = True  # repainting the image of the widget

    def makePreviewCopyDrag(self, event, dropIndex):
        """
        This Method creates a preview of a (copy)move action.
        """

        self.deleteVoidItems()

        dragIndex = self.currentItem().idx()
        self.callback = dropIndex
        event.source = self.source
        self.copydropEvent(event, dropIndex)
        self.copyhelp = dragIndex[:]

        if len(dragIndex) >= len(dropIndex):
            numb = len(dropIndex)-1
            if (dropIndex[0:numb] == dragIndex[0:numb] and
                    dropIndex[numb] <= dragIndex[numb]):
                dragIndex[numb] += 1

        self.setCurrentItem(self.getItem(dragIndex))
        self.calcVoidItems()
        if not self.copyDrag:
            self.setBranchVisible(self.currentItem(), False)
        self.paintactivated = True

    def makePreviewInsert(self, event, dropIndex):
        """
        This method creates a preview of a button drag action.
        """

        if dropIndex == [0]:    # you can't drop anything on the root item
            return

        self.deleteVoidItems()

        self.insertItem(dropIndex)
        new = self.getItem(dropIndex)
        self.setCurrentItem(new)
        self.callback = dropIndex

        self.calcVoidItems()

    def insertItem(self, dropIndex):
        """
        Insert an item as a consequence of a button action.
        """

        idx = dropIndex[0:-1]
        prep = self.getItem(idx)
        self.setCurrentItem(prep)
        idx += [prep.childCount()]
        self.dragSource.sendInsertSignal()
        self.itemMoved.emit(idx, dropIndex)
#        self.emit(QtCore.SIGNAL('itemMoved'), idx, dropIndex)

    def markVoidItems(self, dropIndex=None):
        """
        This method marks all VoidItems, which are children of a VoidItem.
        """

        for voididx in self.voididxlist:
            if dropIndex is not None and len(voididx) >= len(dropIndex):
                numb = len(dropIndex)
                if (dropIndex[0:numb] <= voididx[0:numb]):
                    voididx[numb-1] += 1
                    self.setBranchVoid(self.getItem(voididx), True)
                    voididx[numb-1] -= 1
            else:
                self.setBranchVoid(self.getItem(voididx), True)

    def getItem(self, idx):
        """
        Returns the item at a given item index.
        """

        for item in self.getItemList():
            if item.idx() == idx:
                return item

    def source(self):
        # just for creating the dropevent
        return self

    def updateImage(self):
        # forcing this widget to create a paintEvent
        self.viewport().repaint()

    def calcDropIndex(self, pos):
        """
        This methods finds out, if a dragged item is hovering over another
        item.
        """

        idx = None
        for item in self.getItemList():
            if self.pointInItem(pos, item):
                searched = item
                idx = searched.idx()
                if searched.isVoid:
                    for voididx in self.voididxlist:
                        if len(idx) >= len(voididx):
                            numb = len(voididx)
                            if idx[0:numb] == voididx[0:numb]:
                                idx = voididx
                self.stillInItem = [searched.getType(),
                                    searched.pos, self.minr]
                break

        return idx

    def copydropEvent(self, event, dropIndex=None):
        """
        Make a copy of an Item and then move it to the given dropIndex.
        """

        if event.source() == self:

            dragIndex = self.currentItem().idx()

            if dropIndex is None:
                dropIndex = self.calcDropIndex(event.pos())

            if dropIndex is None:
                return

            tmp = copy.deepcopy(self.xml)
            tmp.copy(dragIndex)
            dragIndex[-1] += 1
            tmp._move(dragIndex, dropIndex)
            status, msg = tmp.checkCommand(dropIndex)

            if status:
                self.itemCopy.emit()
                self.itemMoved.emit(dragIndex, dropIndex)

    def dragEnterEvent(self, e):  # button drag is over the widget
        e.accept()
        self.dragSource = e.source()
        self.dragMod = True
        self.calcVoidItems()
        self.paintactivated = True
        self.updateImage()

    def dragLeaveEvent(self, e):  # button drag leaves the widget
        self.deleteVoidItems()
        self.dragMod = False
        self.dragSource = None
        self.paintactivated = True
        self.updateImage()

    def dragMoveEvent(self, e):
        """
        This method gets called, when the button drag function is used.
        """

        self.previewManager(e)

    def dropEvent(self, event):

        if event.source() == self:      # not a button

            item = self.currentItem()
            dragIndex = item.idx()
            dropIndex = self.calcDropIndex(event.pos())

            if dropIndex is None:
                return

            self.itemMoved.emit(dragIndex, dropIndex)

        else:                           # a button
            if self.callback is None:
                for item in self.getItemList():
                    if self.pointInItem(event.pos(), item):
                        self.setCurrentItem(item)
                        self.treeItemInsert()
                        break
            self.callback = None
            self.dragMod = False
            self.deleteVoidItems()
            self.paintactivated = True
        self.dragMod = False

    def keyPressEvent(self, event):
        """
        Detects if the CopyDrag gets enabled.
        """

        if not self.dragMod:
            super(QTreeWidget, self).keyPressEvent(event)

        if event.key() == QtCore.Qt.Key_Shift:
            if self.dragMod:
                if self.callback is not None:
                    dropIndex = self.callback[:]
                    self.deletePreview()
                    self.copyDrag = True
                    self.makePreview(event, dropIndex)
                else:
                    self.deleteVoidItems()
                    self.copyDrag = True
                    self.calcVoidItems()
                self.paintactivated = True
            else:
                self.nodeCopy = []
                self.copyDrag = True
        self.updateImage()

    def keyReleaseEvent(self, event):
        """
        Detects if the CopyDrag gets disabled.
        """

        if event.key() == QtCore.Qt.Key_Shift:
            if self.dragMod:
                if self.callback is not None:
                    dropIndex = self.callback[:]
                    self.deletePreview()
                    self.copyDrag = False
                    self.makePreview(event, dropIndex)
                else:
                    self.deleteVoidItems()
                    self.copyDrag = False
                    self.calcVoidItems()
                self.needUpdate = True
            else:
                self.copyDrag = False
                self.nodeCopy = []
        self.updateImage()
Example #13
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)
Example #14
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)