def addMovementAnimation(self, animGroup): # print(">>MoveAnim") for phIdx in self.photoIdxsToMove: item = self.photosInGrid[phIdx] anim = QPropertyAnimation(item.pixmap, "pos") anim.setDuration(self.moveDuration - item.gridCol * self.moveModifier) anim.setEasingCurve(QEasingCurve.Linear) startCoords = self.getCellTLCoords(item.gridRow, item.gridCol) endCoords = self.getCellTLCoords(item.gridRow, item.gridCol + self.columnMovementDist) anim.setStartValue(startCoords) anim.setEndValue(endCoords) animGroup.addAnimation(anim)
class MoveSymbol(QUndoCommand): ''' Undo/Redo command for moving symbols ''' def __init__(self, symbol_id, old_pos, new_pos, animate=False): super(MoveSymbol, self).__init__() self.setText('Move symbol') self.symbol = symbol_id self.old_pos = old_pos self.new_pos = new_pos if animate: self.animation = QPropertyAnimation(self.symbol, "position") self.animation.setDuration(500) self.animation.setStartValue(self.old_pos) self.animation.setEndValue(self.new_pos) self.animation.setEasingCurve(QEasingCurve.OutCirc) def undo(self): ''' Undo a symbol move ''' self.symbol.position = self.old_pos try: self.symbol.decisionParent.updateConnectionPointPosition() except AttributeError: pass def redo(self): ''' Apply a symbol move ''' try: self.animation.start() except AttributeError: self.symbol.position = self.new_pos try: self.symbol.decisionParent.updateConnectionPointPosition() except AttributeError: pass
class Tab(QObject): def __init__(self, parent): QObject.__init__(self, parent) self._toolbar = parent self.icon = None self.text = "" self.has_menu = False self.enabled = True self._fader = 0 self._animator = QPropertyAnimation(self) self._animator.setPropertyName(b"fader") self._animator.setTargetObject(self) def fade_in(self): self._animator.stop() self._animator.setDuration(80) self._animator.setEndValue(1) self._animator.start() def fade_out(self): self._animator.stop() self._animator.setDuration(160) self._animator.setEndValue(0) self._animator.start() def _set_fader(self, value): self._fader = value self._toolbar.update() def _get_fader(self): return self._fader fader = pyqtProperty(float, fget=_get_fader, fset=_set_fader)
class MainWindow(QWidget): # class constructor def __init__(self): # call QWidget constructor super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.frame = QFrame(self) self.frame.setFrameStyle(QFrame.Panel | QFrame.Raised) self.frame.setGeometry(150, 30, 100, 100) # create a timer self.timer = QTimer() # set timer timeout callback function self.timer.timeout.connect(self.viewCam) # set control_bt callback clicked function self.ui.control_bt.clicked.connect(self.controlTimer) self.ui.control_bt.clicked.connect(self.animation) # view camera def viewCam(self): # read image in BGR format ret, image = self.cap.read() # convert image to RGB format image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # get image infos height, width, channel = image.shape step = channel * width # create QImage from image qImg = QImage(image.data, width, height, step, QImage.Format_RGB888) # show image in img_label self.ui.image_label.setPixmap(QPixmap.fromImage(qImg)) # start/stop timer def controlTimer(self): # if timer is stopped if not self.timer.isActive(): # create video capture self.cap = cv2.VideoCapture(0) # start timer self.timer.start(20) # update control_bt text self.ui.control_bt.setText("Stop") # if timer is started else: # stop timer self.timer.stop() # release video capture self.cap.release() # update control_bt text self.ui.control_bt.setText("Start") def animation(self): self.anim = QPropertyAnimation(self.frame, b"geometry") self.anim.setDuration(1000) self.anim.setStartValue(QRect(0, 0, 100, 30)) self.anim.setEndValue(QRect(250, 250, 100, 30)) self.anim.start()
class PopWindow(QtWidgets.QWidget): popuphidden = pyqtSignal() def __init__(self): super(PopWindow, self).__init__() self.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setMinimumSize(QSize(100, 50)) self.animation = QPropertyAnimation(self, b"windowOpacity", self) self.animation.finished.connect(self.hide) self.timer = QTimer() self.timer.timeout.connect(self.hideAnimation) self.setupUi() self.text = "" self.setPopupText(self.text) def setupUi(self): self.verticalLayout = QtWidgets.QVBoxLayout(self) self.label = QtWidgets.QLabel(self) font = QFont() font.setPointSize(14) self.label.setFont(font) self.label.setAlignment(Qt.AlignCenter) self.verticalLayout.addWidget(self.label) appearance = self.palette() appearance.setColor(QPalette.Normal, QPalette.Window, Qt.white) self.setPalette(appearance) def setPopupText(self, text): self.label.setText(text) self.label.adjustSize() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.dragPosition = event.globalPos() - self.frameGeometry( ).topLeft() event.accept() def show(self): self.setWindowOpacity(0.0) self.animation.setDuration(1000) self.animation.setStartValue(0.0) self.animation.setEndValue(1.0) QtWidgets.QWidget.show(self) self.animation.start() self.timer.start(2500) def hideAnimation(self): self.timer.stop() self.animation.setDuration(1500) self.animation.setStartValue(1.0) self.animation.setEndValue(0.0) self.animation.start() def hide(self): if self.windowOpacity() == 0: QtWidgets.QWidget.hide(self) self.popuphidden.emit()
class MoreActionsMenu(AeroMenu): """ 更多操作圆角菜单,actionFlag用来指示动作的类型,actionFlag=1有四个动作,actionFlag=0有三个动作 """ def __init__(self, parent=None, actionFlag=1): super().__init__(parent=parent) self.actionFlag = actionFlag # 创建动作和动画 self.createActions() self.animation = QPropertyAnimation(self, b"geometry") # 初始化界面 self.initWidget() def initWidget(self): """ 初始化小部件 """ self.setObjectName("moreActionsMenu") self.animation.setDuration(300) self.animation.setEasingCurve(QEasingCurve.OutQuad) def createActions(self): """ 创建动作""" self.savePlayListAct = QAction( QIcon("app\\resource\\images\\menu\\保存为播放列表.png"), "保存为播放列表", self ) self.clearPlayListAct = QAction( QIcon("app\\resource\\images\\menu\\清空正在播放_16_16.png"), '清空"正在播放"', self ) if self.actionFlag: self.showPlayListAct = QAction( QIcon("app\\resource\\images\\menu\\显示正在播放列表.png"), "显示正在播放列表", self ) self.fillScreenAct = QAction( QIcon("app\\resource\\images\\menu\\转到全屏.png"), "转到全屏", self ) self.action_list = [ self.showPlayListAct, self.fillScreenAct, self.savePlayListAct, self.clearPlayListAct, ] self.actionNum = 4 else: self.showSongerCover = QAction("显示歌手封面", self) self.action_list = [ self.savePlayListAct, self.showSongerCover, self.clearPlayListAct, ] self.actionNum = 3 self.addActions(self.action_list) def exec(self, pos): """ 重写exec_() """ height = self.actionNum * 38 width = [188, 206][self.actionFlag] self.animation.setStartValue(QRect(pos.x(), pos.y(), 1, height)) self.animation.setEndValue(QRect(pos.x(), pos.y(), width, height)) # 开始动画 self.animation.start() super().exec(pos)
def visibility_animation(self, obj, visible): anim = QPropertyAnimation(obj, b'visible') anim.setDuration(0) if visible: anim.setEndValue(1) else: anim.setEndValue(0) return anim
def size_animal(self, obj, old_space, new_space, width, old_position, new_position): # 动画效果 animal = QPropertyAnimation(obj, b'geometry', self) animal.setDuration(200) animal.setStartValue(QRect(*old_position, width, 50 * old_space)) animal.setEndValue(QRect(*new_position, width, 50 * new_space)) animal.start()
def slide_in_animation(self): self.on_display = True ani_in = QPropertyAnimation(self, b'pos', self) ani_in.setDuration(self.ani_duration) ani_in.setStartValue(QPoint(self.x, self.y + self.h)) ani_in.setEndValue(QPoint(self.x, self.y + self.margin_bottom)) ani_in.setEasingCurve(QEasingCurve.InOutQuad) ani_in.start()
def mouseReleaseEvent(self, event): # pylint: disable=invalid-name super().mouseReleaseEvent(event) if event.button() == Qt.LeftButton: anim = QPropertyAnimation(self, b'offset', self) anim.setDuration(120) anim.setStartValue(self.offset) anim.setEndValue(self._end_offset[self.isChecked()]()) anim.start()
def createPositionAnimation(self, item, duration): ani = QPropertyAnimation(item, b'pos', self) ani.setDuration(duration) ani.setStartValue(item.pos()) width = self.squareWidth * 7 ani.setEndValue(QPointF(width - item.x(), width - item.y())) return ani
def anim_delete(self): animation = QPropertyAnimation(self, b'maximumSize') animation.setDuration(750) animation.setStartValue(QSize(315, 50)) animation.setEndValue(QSize(0, 50)) animation.start() self.animation = animation
def _create_animation(self, target, start, end): (x_start, y_start) = start (x_end, y_end) = end animation = QPropertyAnimation(target, "pos".encode('utf-8')) animation.setDuration(self.file_menu_animation_speed) animation.setStartValue(QPoint(x_start, y_start)) animation.setEndValue(QPoint(x_end, y_end)) return animation
def animateClosing(self): self.doneButton.show() animation = QPropertyAnimation(self.doneButton, b"geometry") animation.setDuration(1000) animation.setStartValue(QRect(10, 60, 39, 20)) animation.setEndValue(QRect(120, 60, 39, 20)) animation.start() self.animation = animation
class Frame(QFrame): clicked = pyqtSignal(str) MIN_VALOR = 1 MAX_VALOR = 101 VALOR = MAX_VALOR + MIN_VALOR def __init__(self, parent=None): super(Frame, self).__init__(parent) self.parent = parent self.mover = QPoint() self.habilitado = False def actualizarEstado(self): # Si la posicion x del boton mas la mitad de su ancho # es menor que la mitad del ancho del widget padre, # entonces esta apagado (NO) if (self.parent.button.x() + (self.parent.button.width() / 2)) < Frame.VALOR / 2: self.habilitado = False # Si la posicion x del boton mas la mitad de su ancho # es mayor que la mitad del ancho del widget padre, # entonces esta encendido (SI) if (self.parent.button.x() + (self.parent.button.width() / 2)) > Frame.VALOR / 2: self.habilitado = True if self.habilitado: self.parent.button.setText("SI") color = QColor(206, 61, 59) elif not self.habilitado: self.parent.button.setText("NO") color = QColor(147, 183, 89) colorFrame = self.palette() colorFrame.setColor(QPalette.Background, color) self.setPalette(colorFrame) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.mover.setY(1) if event.pos().x() < Frame.VALOR / 2: self.mover.setX(Frame.MIN_VALOR) elif event.pos().x() > Frame.VALOR / 2: self.mover.setX(Frame.MAX_VALOR - self.parent.button.width()) self.animacion = QPropertyAnimation(self.parent.button, b"pos") self.animacion.setDuration(150) self.animacion.setEndValue(self.mover) self.animacion.valueChanged.connect(self.actualizarEstado) self.animacion.finished.connect(self.emitirEstado) self.animacion.start(QAbstractAnimation.DeleteWhenStopped) def emitirEstado(self): self.clicked.emit(self.parent.button.text())
def __init__(self, scatter): super(ScatterDataModifier, self).__init__() self.m_graph = scatter self.m_inputHandler = CustomInputHandler() self.m_graph.activeTheme().setType(Q3DTheme.ThemeDigia) self.m_graph.setShadowQuality(QAbstract3DGraph.ShadowQualityMedium) self.m_graph.scene().activeCamera().setCameraPreset( Q3DCamera.CameraPresetFront) self.m_graph.setAxisX(QValue3DAxis()) self.m_graph.setAxisY(QValue3DAxis()) self.m_graph.setAxisZ(QValue3DAxis()) self.m_graph.axisX().setRange(-10.0, 10.0) self.m_graph.axisY().setRange(-5.0, 5.0) self.m_graph.axisZ().setRange(-5.0, 5.0) series = QScatter3DSeries() series.setItemLabelFormat("@xLabel, @yLabel, @zLabel") series.setMesh(QAbstract3DSeries.MeshCube) series.setItemSize(0.15) self.m_graph.addSeries(series) self.m_animationCameraX = QPropertyAnimation( self.m_graph.scene().activeCamera(), 'xRotation') self.m_animationCameraX.setDuration(20000) self.m_animationCameraX.setStartValue(0.0) self.m_animationCameraX.setEndValue(360.0) self.m_animationCameraX.setLoopCount(-1) upAnimation = QPropertyAnimation(self.m_graph.scene().activeCamera(), 'yRotation') upAnimation.setDuration(9000) upAnimation.setStartValue(5.0) upAnimation.setEndValue(45.0) downAnimation = QPropertyAnimation(self.m_graph.scene().activeCamera(), 'yRotation') downAnimation.setDuration(9000) downAnimation.setStartValue(45.0) downAnimation.setEndValue(5.0) self.m_animationCameraY = QSequentialAnimationGroup() self.m_animationCameraY.setLoopCount(-1) self.m_animationCameraY.addAnimation(upAnimation) self.m_animationCameraY.addAnimation(downAnimation) self.m_animationCameraX.start() self.m_animationCameraY.start() self.m_graph.setActiveInputHandler(self.m_inputHandler) self.m_selectionTimer = QTimer() self.m_selectionTimer.setInterval(10) self.m_selectionTimer.timeout.connect(self.triggerSelection) self.m_selectionTimer.start()
class NavigationMenu(NavigationWidget): """ 导航菜单 """ def __init__(self, parent=None): super().__init__(parent) # 是否削减设置按钮底部空白标志位 self.__isShowBottomSpacing = False self.__ani = QPropertyAnimation(self, b"geometry") # 才叫你窗口效果 self.windowEffect = WindowEffect() self.__initWidget() def __initWidget(self): """ 初始化小部件 """ self.resize(60, 800) self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(Qt.NoDropShadowWindowHint | Qt.Popup) # self.hWnd = HWND(int(self.winId())) self.windowEffect.setAcrylicEffect(self.winId(), "F2F2F299", False) def resizeEvent(self, e): """ 调整小部件尺寸 """ super().resizeEvent(e) self.settingButton.move( 0, self.height() - 62 - 10 - self.__isShowBottomSpacing * 115 ) self.searchLineEdit.resize(self.width() - 30, self.searchLineEdit.height()) def aniShow(self): """ 动画显示 """ super().show() self.__ani.setStartValue(QRect(self.x(), self.y(), 60, self.height())) self.__ani.setEndValue(QRect(self.x(), self.y(), 400, self.height())) self.__ani.setDuration(85) self.__ani.start() self.__ani.setEasingCurve(QEasingCurve.InOutQuad) def aniHide(self): """ 动画隐藏 """ self.__ani.setStartValue(QRect(self.x(), self.y(), 400, self.height())) self.__ani.setEndValue(QRect(self.x(), self.y(), 60, self.height())) self.__ani.finished.connect(self.__hideAniFinishedSlot) self.__ani.setDuration(85) self.__ani.start() def __hideAniFinishedSlot(self): """ 隐藏窗体的动画结束 """ super().hide() self.resize(60, self.height()) self.__ani.disconnect() def setBottomSpacingVisible(self, isBottomSpacingVisible: bool): """ 是否削减设置按钮底部空白 """ self.__isShowBottomSpacing = isBottomSpacingVisible @property def isShowBottomSpacing(self): return self.__isShowBottomSpacing
class MyDialog(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.pixmap = QPixmap() self.pixmap.load('game_map.png') self.item = QGraphicsPixmapItem(self.pixmap) self.scene = QGraphicsScene() self.scene.addItem(self.item) self.ui.graphicsView.setScene(self.scene) self.ui.pushButton.clicked.connect(self.startanimation) self.path = QPainterPath() self.path.moveTo(30,30) self.path.cubicTo(30,30,80,180,180,170) self.ui.label.pos = QPointF(20,20) self.pos1 = [0,0] self.pos2 = [0,0] def mousePressEvent(self, event): if event.buttons() & QtCore.Qt.LeftButton: self.pos1[0] = event.x() self.pos1[1] = event.y() def mouseReleaseEvent(self, event): self.pos2[0] = event.x() self.pos2[1] = event.y() self.update() def paintEvent(self, event): width = self.pos2[0] - self.pos1[0] height = self.pos2[1] - self.pos1[1] rect = QRect(self.pos1[0],self.pos1[1],width,height) qp = QPainter() qp.begin(self) pen = QPen(Qt.red,3) pen.setStyle(Qt.DotLine) qp.setPen(pen) qp.drawArc(rect,0,360*16) qp.end() # def paintEvent(self,e): # qp = QPainter() # qp.begin(self) # qp.drawPath(self.path) # qp.end() def startanimation(self): self.anim = QPropertyAnimation(self.ui.label, b'pos') self.anim.setDuration(4000) self.anim.setStartValue(QPointF(20,20)) pos = [n/80 for n in range(0,50)] for i in pos: self.anim.setKeyValueAt(i,self.path.pointAtPercent(i)) self.anim.setEndValue(QPointF(160,150)) self.anim.start()
class FancyButton(QToolButton): def __init__(self, text="", parent=None): super().__init__(parent) self.setAttribute(Qt.WA_Hover, True) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) if text: self.setText(text) self._fader = 0 def _set_fader(self, value): self._fader = value self.update() def _get_fader(self): return self._fader fader = pyqtProperty(float, fget=_get_fader, fset=_set_fader) def event(self, event): if event.type() == QEvent.Enter: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(150) self.anim.setEndValue(1.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) elif event.type() == QEvent.Leave: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(124) self.anim.setEndValue(0.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) else: return QToolButton.event(self, event) return False def paintEvent(self, event): painter = QPainter(self) if self.isEnabled() and not self.isDown() and not self.isChecked(): painter.save() hover_color = QColor("#424242") faded_hover_color = QColor(hover_color) faded_hover_color.setAlpha(int(self._fader * hover_color.alpha())) painter.fillRect(event.rect(), faded_hover_color) painter.restore() elif self.isDown() or self.isChecked(): painter.save() selected_color = QColor("#090909") painter.fillRect(event.rect(), selected_color) painter.restore() fm = QFontMetrics(painter.font()) rect = QRect(-3, 0, self.rect().width(), fm.height()) icon_rect = QRect(0, 0, 22, 22) self.icon().paint(painter, icon_rect, Qt.AlignVCenter) painter.drawText(rect, Qt.AlignRight | Qt.AlignVCenter, self.text()) def sizeHint(self): self.ensurePolished() s = self.fontMetrics().size(Qt.TextSingleLine, self.text()) s.setWidth(s.width() + 25) return s.expandedTo(QApplication.globalStrut())
def slideInWidget(self, widget, direction=Automatic): if self.indexOf(widget) == -1 or widget is self.currentWidget(): return if self._active: return self._active = True prev_widget = self.currentWidget() next_widget = widget if direction == self.Automatic: if self.indexOf(prev_widget) < self.indexOf(next_widget): direction = self.BottomToTop if self.verticalMode else self.RightToLeft else: direction = self.TopToBottom if self.verticalMode else self.LeftToRight width = self.frameRect().width() height = self.frameRect().height() # the following is important, to ensure that the new widget has correct geometry information when sliding in the first time next_widget.setGeometry(0, 0, width, height) if direction in (self.TopToBottom, self.BottomToTop): offset = QPoint( 0, height if direction == self.TopToBottom else -height) elif direction in (self.LeftToRight, self.RightToLeft): offset = QPoint(width if direction == self.LeftToRight else -width, 0) # re-position the next widget outside of the display area prev_widget_position = prev_widget.pos() next_widget_position = next_widget.pos() next_widget.move(next_widget_position - offset) next_widget.show() next_widget.raise_() prev_widget_animation = QPropertyAnimation(prev_widget, "pos") prev_widget_animation.setDuration(self.animationDuration) prev_widget_animation.setEasingCurve( QEasingCurve(self.animationEasingCurve)) prev_widget_animation.setStartValue(prev_widget_position) prev_widget_animation.setEndValue(prev_widget_position + offset) next_widget_animation = QPropertyAnimation(next_widget, "pos") next_widget_animation.setDuration(self.animationDuration) next_widget_animation.setEasingCurve( QEasingCurve(self.animationEasingCurve)) next_widget_animation.setStartValue(next_widget_position - offset) next_widget_animation.setEndValue(next_widget_position) self._animation_group.clear() self._animation_group.addAnimation(prev_widget_animation) self._animation_group.addAnimation(next_widget_animation) self._animation_group.start()
class ClickableLabel(QLabel): """Class that extends the functionality of the QLabel adding mouse events""" clicked = pyqtSignal() in_label = False SLOW_DURATION = 1500 FAST_DURATION = 500 def __init__(self, parent=None): """Constructor of the class Keyword Arguments: parent {ui.gui.views.main_view.world_selection.WorldSelection} -- Parent of this widget (default: {None}) """ QLabel.__init__(self, parent) self.start_animation(self.SLOW_DURATION) def start_animation(self, duration): """Start a fadein-fadeout animation Arguments: duration {int} -- Duration of millisecondns of each fadein-fadeout cycle of the animation. """ self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) self.animation1 = QPropertyAnimation(self.effect, b"opacity") self.animation1.setDuration(duration) self.animation1.setStartValue(1) self.animation1.setEndValue(0) self.animation2 = QPropertyAnimation(self.effect, b"opacity") self.animation2.setDuration(duration) self.animation2.setStartValue(0) self.animation2.setEndValue(1) self.ga = QSequentialAnimationGroup() self.ga.addAnimation(self.animation1) self.ga.addAnimation(self.animation2) self.ga.setLoopCount(-1) self.ga.start() def enterEvent(self, event): """Mouse event when entering the widget""" self.ga.stop() self.start_animation(self.FAST_DURATION) def leaveEvent(self, event): """Mouse event when leaving the widget""" self.ga.stop() self.start_animation(self.SLOW_DURATION) def end_animation(self): """Finish the fade animation""" self.ga.stop() self.hide()
def moveSlider(self): animation = QPropertyAnimation(self) animation.setTargetObject(self.line_label) animation.setPropertyName(b"geometry") animation.setStartValue(self.line_label.geometry()) geo = self.sender().geometry() animation.setEndValue(QRect(geo.x(), 76, geo.width(), 4)) animation.setDuration(200) animation.start()
def move(self, r1: Rectangle, r2: Rectangle): r1.in_animation = True animation = QPropertyAnimation(r1, b"pos") animation.setDuration(self.duration) animation.setStartValue(QPointF(r1.x(), r1.y())) animation.setEndValue(QPointF(r2.x(), r2.y())) animation.setLoopCount(1) self.animations.append(animation) animation.start()
class SwitchPrivate(QObject): def __init__(self, q, parent=None, isOn=False): self.isOn = isOn QObject.__init__(self, parent=parent) self.mPointer = q if self.isOn: self.mPosition = 1.0 else: self.mPosition = 0.0 self.mGradient = QLinearGradient() self.mGradient.setSpread(QGradient.PadSpread) self.animation = QPropertyAnimation(self) self.animation.setTargetObject(self) self.animation.setPropertyName(b'position') self.animation.setStartValue(0.0) self.animation.setEndValue(1.0) self.animation.setDuration(200) self.animation.setEasingCurve(QEasingCurve.InOutExpo) self.animation.finished.connect(self.mPointer.update) @pyqtProperty(float) def position(self): return self.mPosition @position.setter def position(self, value): self.mPosition = value self.mPointer.update() def draw(self, painter): r = self.mPointer.rect() margin = r.height() / 10 painter.setPen(Qt.NoPen) self.background_color = QColor(118, 118, 118) painter.setBrush(self.background_color) painter.drawRoundedRect(r, r.height() / 2, r.height() / 2) self.mGradient = QColor(35, 35, 35) painter.setBrush(self.mGradient) x = r.height() / 2.0 + self.mPosition * (r.width() - r.height()) painter.drawEllipse(QPointF(x, r.height() / 2), r.height() / 2 - margin, r.height() / 2 - margin) @pyqtSlot(bool, name='animate') def animate(self, checked): self.animation.setDirection(QPropertyAnimation.Forward if checked else QPropertyAnimation.Backward) self.animation.start()
def fade(self, widget): self.effect = QGraphicsOpacityEffect() widget.setGraphicsEffect(self.effect) animation = QPropertyAnimation(self.effect, b"opacity") animation.setDuration(1000) animation.setStartValue(1) animation.setEndValue(0) animation.start() self.animations.append(animation)
def createAnimation(self, target, index): '''创建动画''' # 暂停动画一 PauseAnimation1 = QPauseAnimation(target) PauseAnimation1.setDuration(150 * index) # 并行动画组一 # #透明度动画一 OpacityAnimation1 = QPropertyAnimation(target, b"opacity") OpacityAnimation1.setDuration(400) OpacityAnimation1.setStartValue(0) OpacityAnimation1.setEndValue(1) # #移动动画一 MoveAnimation1 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation1.setMoveType(_MoveAnimation.MOVE1) MoveAnimation1.setDuration(400) MoveAnimation1.setStartValue(QPoint(0, 0)) MoveAnimation1.setEndValue(QPoint(self.parent.width() / 4.0, 0)) # 添加到并行动画里面 ParallelAnimation1 = QParallelAnimationGroup() ParallelAnimation1.addAnimation(OpacityAnimation1) ParallelAnimation1.addAnimation(MoveAnimation1) # 移动动画二 MoveAnimation2 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation2.setMoveType(_MoveAnimation.MOVE2) MoveAnimation2.setDuration(2000) MoveAnimation2.setEndValue(QPoint((self.parent.width() / 4.0) * 3.0, 0)) # 并行动画组二 # #透明度动画二 OpacityAnimation2 = QPropertyAnimation(target, b"opacity") OpacityAnimation2.setDuration(400) OpacityAnimation2.setStartValue(1) OpacityAnimation2.setEndValue(0) # #移动动画三 MoveAnimation3 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation3.setMoveType(_MoveAnimation.MOVE3) MoveAnimation3.setDuration(400) MoveAnimation3.setEndValue(QPoint(self.parent.width(), 0)) # 添加到并行动画里面 ParallelAnimation2 = QParallelAnimationGroup() ParallelAnimation2.addAnimation(OpacityAnimation2) ParallelAnimation2.addAnimation(MoveAnimation3) # 暂停动画二 PauseAnimation2 = QPauseAnimation(target) PauseAnimation2.setDuration(150 * (5 - index - 1)) # 串行动画组 self.setLoopCount(-1) # 无限循环 self.addAnimation(PauseAnimation1) self.addAnimation(ParallelAnimation1) self.addAnimation(MoveAnimation2) self.addAnimation(ParallelAnimation2) self.addAnimation(PauseAnimation2)
class MoreActionsMenu(QMenu): """ 更多操作菜单 """ def __init__(self, parent=None): super().__init__(parent) # 添加动画 self.animation = QPropertyAnimation(self, b"geometry") # 创建窗口效果实例 self.windowEffect = WindowEffect() self.__initWidget() def __initWidget(self): """ 初始化小部件 """ self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup | Qt.NoDropShadowWindowHint) self.setObjectName("albumInterfaceMoreActionMenu") self.animation.setDuration(300) self.animation.setEasingCurve(QEasingCurve.OutQuad) # 设置层叠样式 self.__setQss() def event(self, e: QEvent): if e.type() == QEvent.WinIdChange: # self.hWnd = HWND(int(self.winId())) self.windowEffect.addShadowEffect(self.winId()) return QMenu.event(self, e) def __setQss(self): """ 设置层叠样式 """ with open("app\\resource\\css\\menu.qss", encoding="utf-8") as f: self.setStyleSheet(f.read()) def setActionNum(self, actionNum): """ 设置动作的个数 """ self.clear() self.actionNum = actionNum self.action_list = [] self.deleteAct = QAction("删除", self) self.action_list.append(self.deleteAct) if actionNum >= 2: self.editInfoAct = QAction("编辑信息", self) self.action_list.append(self.editInfoAct) if actionNum == 3: self.pinToStartMenuAct = QAction('固定到"开始"菜单', self) self.action_list.append(self.pinToStartMenuAct) self.addActions(self.action_list[::-1]) self.currentWidth = [120, 120, 168][self.actionNum - 1] self.currentHeight = self.actionNum * 38 + 10 def exec(self, pos): """ 显示菜单 """ self.animation.setStartValue( QRect(pos.x(), pos.y(), 1, self.currentHeight)) self.animation.setEndValue( QRect(pos.x(), pos.y(), self.currentWidth, self.currentHeight)) # 开始动画 self.animation.start() super().exec(pos)
def move_animation(self, car, x1, y1, x2, y2, cost=1): animation = QPropertyAnimation(self, propertyName=b'pos') animation.setParent(self) animation.setTargetObject(car) animation.setDuration(cost * 1000) animation.setStartValue(QPoint(x1, y1)) animation.setEndValue(QPoint(x2, y2)) # animation.start() return animation
def translation_animation(self, obj, func, duration=1000): anim = QPropertyAnimation(obj, b'pos') anim.setDuration(duration) anim.setStartValue(QPointF(func(0)[0], func(0)[1])) anim.setEndValue(QPointF(func(1)[0], func(1)[1])) vals = [p / 100 for p in range(0, 101)] for i in vals: anim.setKeyValueAt(i, (QPointF(func(i)[0], func(i)[1]))) return anim
def splash_open_init(pane): animation = QPropertyAnimation(pane) animation.setTargetObject(pane) animation.setPropertyName(b"pos") animation.setStartValue(pane.pos()) animation.setEndValue(QPoint(0, 0)) animation.setEasingCurve(QEasingCurve.OutBounce) animation.setDuration(500) animation.start(QAbstractAnimation.DeleteWhenStopped)
def splash_exit_init(pane, pane1): animation = QPropertyAnimation(pane) animation.setTargetObject(pane) animation.setPropertyName(b"pos") animation.setEndValue(QPoint(0, pane1.width())) animation.setStartValue(QPoint(0, 0)) animation.setEasingCurve(QEasingCurve.InBounce) animation.setDuration(500) animation.start(QAbstractAnimation.DeleteWhenStopped)
class MenuBar(QTabWidget): def __init__(self, parent=None): super(MenuBar, self).__init__(parent) tabbar = TabBar(parent) self.setTabBar(tabbar) self.setMinimumHeight(135) self.setMouseTracking(True) self._drop = False self.currentChanged.connect(self.currentChangedFunc) def currentChangedFunc(self, index): tab_text = self.tabText(index) menu = self.findChild(MenuWidget, tab_text) self.anim = QPropertyAnimation(menu, b'_height') self.anim.setDuration(100) self.anim.setStartValue(0) self.anim.setEndValue(100) self.anim.start() def addMenu(self, p_str): p_str = " {p_str} ".format(p_str=p_str) menu = MenuWidget() menu.setObjectName(p_str) self.addTab(menu, p_str) self.hlayout = QHBoxLayout(menu) self.hlayout.setObjectName(p_str) self.hlayout.setContentsMargins(0, 0, 0, 0) self.hlayout.setSpacing(0) hs = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hlayout.addItem(hs) return (menu) def addGroup(self, p_str, menu): group = GroupWidget(p_str, menu) group.setObjectName('group') insert_index = len(menu.findChildren(GroupWidget, 'group')) - 1 self.hlayout.insertWidget(insert_index, group) return (group) def listGroups(self, menu): self.group_list = [] for i in range(self.hlayout.count()): try: w = self.hlayout.itemAt(i).widget() self.group_list.append(w._title) except: AttributeError return (self.group_list) def addSliderChoiceWidget(self, menu): slider_choice = SliderChoiceWidget() insert_index = len(menu.findChildren(GroupWidget, 'group')) self.hlayout.insertWidget(insert_index, slider_choice) return (slider_choice)
def createAnimation(self, target, index): '''创建动画''' # 暂停动画一 PauseAnimation1 = QPauseAnimation(target) PauseAnimation1.setDuration(150 * index) # 并行动画组一 # #透明度动画一 OpacityAnimation1 = QPropertyAnimation(target, b"opacity") OpacityAnimation1.setDuration(400) OpacityAnimation1.setStartValue(0) OpacityAnimation1.setEndValue(1) # #移动动画一 MoveAnimation1 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation1.setMoveType(_MoveAnimation.MOVE1) MoveAnimation1.setDuration(400) MoveAnimation1.setStartValue(QPoint(0, 0)) MoveAnimation1.setEndValue(QPoint(self.parent.width() / 4.0, 0)) # 添加到并行动画里面 ParallelAnimation1 = QParallelAnimationGroup() ParallelAnimation1.addAnimation(OpacityAnimation1) ParallelAnimation1.addAnimation(MoveAnimation1) # 移动动画二 MoveAnimation2 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation2.setMoveType(_MoveAnimation.MOVE2) MoveAnimation2.setDuration(2000) MoveAnimation2.setEndValue(QPoint((self.parent.width() / 4.0) * 3.0, 0)) # 并行动画组二 # #透明度动画二 OpacityAnimation2 = QPropertyAnimation(target, b"opacity") OpacityAnimation2.setDuration(400) OpacityAnimation2.setStartValue(1) OpacityAnimation2.setEndValue(0) # #移动动画三 MoveAnimation3 = _MoveAnimation(target, self.parent, self.easing) MoveAnimation3.setMoveType(_MoveAnimation.MOVE3) MoveAnimation3.setDuration(400) MoveAnimation3.setEndValue(QPoint(self.parent.width(), 0)) # 添加到并行动画里面 ParallelAnimation2 = QParallelAnimationGroup() ParallelAnimation2.addAnimation(OpacityAnimation2) ParallelAnimation2.addAnimation(MoveAnimation3) # 暂停动画二 PauseAnimation2 = QPauseAnimation(target) PauseAnimation2.setDuration(150 * (5 - index - 1)) # 串行动画组 self.setLoopCount(-1) # 无限循环 self.addAnimation(PauseAnimation1) self.addAnimation(ParallelAnimation1) self.addAnimation(MoveAnimation2) self.addAnimation(ParallelAnimation2) self.addAnimation(PauseAnimation2)
def zoom2(self): animation = QPropertyAnimation(self, b"geometry", parent=self.parent()) animation.setDuration(200) animation.setStartValue( QRect(self.x(), self.y() + 10, self.width(), self.height())) animation.setEndValue( QRect(self.x(), self.y(), self.width(), self.height())) animation.setEasingCurve(QEasingCurve.OutBounce) animation.start()
def fadeOut(self): g = QGraphicsOpacityEffect(self) self.errorWidget.setGraphicsEffect(g) a = QPropertyAnimation(g, self.animationProp, self) a.setDuration(350) a.setStartValue(1) a.setEndValue(0) a.setEasingCurve(QEasingCurve.OutBack) a.finished.connect(lambda: self.errorWidget.setVisible(False)) a.start(QPropertyAnimation.DeleteWhenStopped)
def __init__(self): super(Robot, self).__init__() self.setFlag(self.ItemHasNoContents) self.torsoItem = RobotTorso(self) self.headItem = RobotHead(self.torsoItem) self.upperLeftArmItem = RobotLimb(self.torsoItem) self.lowerLeftArmItem = RobotLimb(self.upperLeftArmItem) self.upperRightArmItem = RobotLimb(self.torsoItem) self.lowerRightArmItem = RobotLimb(self.upperRightArmItem) self.upperRightLegItem = RobotLimb(self.torsoItem) self.lowerRightLegItem = RobotLimb(self.upperRightLegItem) self.upperLeftLegItem = RobotLimb(self.torsoItem) self.lowerLeftLegItem = RobotLimb(self.upperLeftLegItem) settings = ( # Item Position Rotation Scale # x y start end (self.headItem, 0, -18, 20, -20, 1.1), (self.upperLeftArmItem, -15, -10, 190, 180, 0), (self.lowerLeftArmItem, 30, 0, 50, 10, 0), (self.upperRightArmItem, 15, -10, 300, 310, 0), (self.lowerRightArmItem, 30, 0, 0, -70, 0), (self.upperRightLegItem, 10, 32, 40, 120, 0), (self.lowerRightLegItem, 30, 0, 10, 50, 0), (self.upperLeftLegItem, -10, 32, 150, 80, 0), (self.lowerLeftLegItem, 30, 0, 70, 10, 0), (self.torsoItem, 0, 0, 5, -20, 0), ) animation = QParallelAnimationGroup(self) for item, pos_x, pos_y, start_rot, end_rot, scale in settings: item.setPos(pos_x, pos_y) rot_animation = QPropertyAnimation(item, b"rotation") rot_animation.setStartValue(start_rot) rot_animation.setEndValue(end_rot) rot_animation.setEasingCurve(QEasingCurve.SineCurve) rot_animation.setDuration(2000) animation.addAnimation(rot_animation) if scale > 0: scale_animation = QPropertyAnimation(item, b"scale") scale_animation.setEndValue(scale) scale_animation.setEasingCurve(QEasingCurve.SineCurve) scale_animation.setDuration(2000) animation.addAnimation(scale_animation) animation.setLoopCount(-1) animation.start()
class CircleObstruction(QColorThemedGraphicsObject): """ Useful for notifications, I...guess? """ def get_thickness(self): return self._thickness def set_thickness(self,c): self._thickness = c self.update() thickness = pyqtProperty(float, get_thickness, set_thickness) def __init__(self, sz, thickness, parent=None): super(CircleObstruction, self).__init__(parent) self._sz = sz self._thickness = thickness self._color = Qt.blue def boundingRect(self): return QRectF(-self._thickness, -self._thickness, self._sz + 2*self._thickness, self._sz + 2*self._thickness) def paint(self, painter, option, widget): # painter.setPen(QPen(self._color, # self._thickness)) painter.setBrush(self._color) painter.setPen(Qt.NoPen) painter.drawEllipse(QRectF( self._sz/2.0 - self._thickness, self._sz/2.0 - self._thickness, 2*self._thickness, 2*self._thickness, )) def show_anim(self): self.anim = QPropertyAnimation(self, "thickness") self.anim.setDuration(2000) self.anim.setStartValue(self.get_thickness()) self.anim.setEndValue(50.0) self.anim.setEasingCurve(QEasingCurve.OutElastic) self.anim.start() def hide_anim(self): self.anim = QPropertyAnimation(self, "thickness") self.anim.setDuration(500) self.anim.setStartValue(self.get_thickness()) self.anim.setEndValue(0.0) self.anim.setEasingCurve(QEasingCurve.InBack) self.anim.start()
class NotifyWidget(QWidget): def __init__(self): super().__init__() self.layout = QVBoxLayout(self) self.sub_widget = _NotifySubWidget(self) self.layout.addWidget(self.sub_widget) self.layout.setContentsMargins(0, 0, 0, 0) self._exit_shortcut = QShortcut(QKeySequence(Qt.Key_Escape), self) self._exit_shortcut.activated.connect(self.close) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool) self.setAttribute(Qt.WA_TranslucentBackground) self.setAttribute(Qt.WA_MacAlwaysShowToolWindow) self.resize(width, height) self.move(QApplication.desktop().width() - self.width() - 20, 40) self.setLayout(self.layout) self._animation = QPropertyAnimation(self, b'windowOpacity') self._animation.setStartValue(0.8) self._animation.setKeyValueAt(0.4, 1) self._animation.setEndValue(0) self._animation.setDuration(5000) self._animation.finished.connect(self.close) def show(self): super().show() self._animation.start() def show_message(self, title, content, pixmap=None): if not self.isVisible(): self.show() self._animation.stop() self._animation.setCurrentTime(0) self._animation.start() self.sub_widget.set_title(title) self.sub_widget.set_content(content) pixmap = pixmap if pixmap else QPixmap(WINDOW_ICON) self.sub_widget.set_pixmap(pixmap) def enterEvent(self, event): self._animation.setCurrentTime(0)
def addRemovalAnimation(self, animGroup): # print(">>RemoveAnim") for phIdx in self.photoIdxsToRemove: item = self.photosInGrid[phIdx] anim = QPropertyAnimation(item.pixmap, "scale") anim.setDuration(self.shrinkDuration) anim.setEasingCurve(QEasingCurve.Linear) anim.setStartValue(1.0) anim.setEndValue(0.0) animGroup.addAnimation(anim) anim = QPropertyAnimation(item.pixmap, "pos") anim.setDuration(self.shrinkDuration) anim.setEasingCurve(QEasingCurve.Linear) startCoords = self.getCellTLCoords(item.gridRow, item.gridCol) endCoords = QPointF(startCoords.x()+self.cellSize.width()*item.xFactor, startCoords.y() + item.pixmap.pixmapSize.height() / 2) anim.setStartValue(startCoords) anim.setEndValue(endCoords) animGroup.addAnimation(anim)
def animate(self, item, property_name, duration, start_value, end_value): """Summary Args: item (TYPE): Description property_name (TYPE): Description duration (TYPE): Description start_value (TYPE): Description end_value (TYPE): Description """ if item is not None: b_name = property_name.encode('ascii') anim = QPropertyAnimation(item.adapter, b_name) anim.setDuration(duration) anim.setStartValue(start_value) anim.setEndValue(end_value) anim.start() item.adapter.saveRef(property_name, anim)
def animate(self, item: QGraphicsItem, property_name: str, duration: int, start_value, end_value): """ Args: item: Description property_name: Description duration: Description start_value (QVariant): Description end_value (QVariant): Description """ b_name = property_name.encode('ascii') anim = item.adapter.getRef(property_name) if anim is None: anim = QPropertyAnimation(item.adapter, b_name) item.adapter.saveRef(property_name, anim) anim.setDuration(duration) anim.setStartValue(start_value) anim.setEndValue(end_value) anim.start()
def addInsertionAnimation(self, animGroup): # Animation for added # print(">>>InsAnim") for ph in self.picItemsToAdd: # Set pixmap start location newPixmap = ph[0].pixmap row = ph[1] col = ph[2] xFact = ph[0].xFactor endCoords = self.getCellTLCoords(row, col) startCoords = QPointF(endCoords.x()-self.cellSize.width()*xFact, endCoords.y()) newPixmap.pixmap_item.setPos(startCoords) newPixmap.pixmap_item.setVisible(True) # Animate in anim = QPropertyAnimation(newPixmap, "pos") anim.setDuration(self.insertDuration) anim.setStartValue(startCoords) anim.setEasingCurve(QEasingCurve.Linear) anim.setEndValue(endCoords) animGroup.addAnimation(anim)
class ChannelListItem(QWidget): """ This class is responsible for managing the item in the list of channels. The list item supports a fade-in effect, which can be enabled with the should_fade parameter in the constructor. """ def __init__(self, parent, channel, fade_delay=0, should_fade=False): super(QWidget, self).__init__(parent) uic.loadUi('qt_resources/channel_list_item.ui', self) self.channel_name.setText(channel["name"]) self.channel_description_label.setText("Active 6 days ago • %d items" % channel["torrents"]) self.channel_num_subs_label.setText(str(channel["votes"])) if channel["sub"]: self.channel_subscribe_button.setText("✓ subscribed") else: self.channel_subscribe_button.setText("subscribe") if should_fade: self.opacity_effect = QGraphicsOpacityEffect(self) self.opacity_effect.setOpacity(0) self.setGraphicsEffect(self.opacity_effect) self.timer = QTimer() self.timer.setInterval(fade_delay) self.timer.timeout.connect(self.fadeIn) self.timer.start() def fadeIn(self): self.anim = QPropertyAnimation(self.opacity_effect, 'opacity') self.anim.setDuration(800) self.anim.setStartValue(0) self.anim.setEndValue(1) self.anim.start() self.timer.stop()
class Preferences(QDialog): # Signal to warn that the window is closed settingsClosed = pyqtSignal() def __init__(self, parent=None): super(Preferences, self).__init__(parent) # Main container # This contains a grid main_box = QVBoxLayout(self) main_box.setContentsMargins(200, 50, 200, 100) # The grid contains two containers # left container and right container grid = QGridLayout() # Left Container left_container = QVBoxLayout() left_container.setContentsMargins(0, 0, 0, 0) # General group_gral = QGroupBox(self.tr("General")) box_gral = QVBoxLayout(group_gral) # Updates btn_updates = QPushButton(self.tr("Check for updates")) box_gral.addWidget(btn_updates) # Language group_language = QGroupBox(self.tr("Language")) box = QVBoxLayout(group_language) # Find .qm files in language path available_langs = file_manager.get_files_from_folder( settings.LANGUAGE_PATH) languages = ["English"] + available_langs self._combo_lang = QComboBox() box.addWidget(self._combo_lang) self._combo_lang.addItems(languages) self._combo_lang.currentIndexChanged[int].connect( self._change_lang) if PSetting.LANGUAGE: self._combo_lang.setCurrentText(PSetting.LANGUAGE) box.addWidget(QLabel(self.tr("(Requires restart)"))) # Add widgets left_container.addWidget(group_gral) left_container.addWidget(group_language) left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Right Container right_container = QVBoxLayout() right_container.setContentsMargins(0, 0, 0, 0) # Editor editor_group = QGroupBox(self.tr("Editor Configurations")) box_editor = QHBoxLayout(editor_group) # Current line self._highlight_current_line = QCheckBox( self.tr("Highlight Current Line")) self._highlight_current_line.setChecked( PSetting.HIGHLIGHT_CURRENT_LINE) self._highlight_current_line.stateChanged[int].connect( self.__current_line_value_changed) box_editor.addWidget(self._highlight_current_line) # Matching paren self._matching_paren = QCheckBox(self.tr("Matching Parenthesis")) self._matching_paren.setChecked( PSetting.MATCHING_PARENTHESIS) self._matching_paren.stateChanged[int].connect( self.__set_enabled_matching_parenthesis) box_editor.addWidget(self._matching_paren) # Font group font_group = QGroupBox(self.tr("Font")) font_grid = QGridLayout(font_group) font_grid.addWidget(QLabel(self.tr("Family")), 0, 0) self._combo_font = QFontComboBox() self._combo_font.setCurrentFont(PSetting.FONT) font_grid.addWidget(self._combo_font, 0, 1) font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0) self._combo_font_size = QComboBox() fdb = QFontDatabase() combo_sizes = fdb.pointSizes(PSetting.FONT.family()) current_size_index = combo_sizes.index( PSetting.FONT.pointSize()) self._combo_font_size.addItems([str(f) for f in combo_sizes]) self._combo_font_size.setCurrentIndex(current_size_index) font_grid.addWidget(self._combo_font_size, 1, 1) right_container.addWidget(editor_group) right_container.addWidget(font_group) right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Add widgets grid.addLayout(left_container, 0, 0) grid.addLayout(right_container, 0, 1) main_box.addLayout(grid) # Button close and reset hbox = QHBoxLayout() hbox.setSpacing(20) hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_cancel = QPushButton(self.tr("Back")) hbox.addWidget(btn_cancel) btn_reset = QPushButton(self.tr("Reset Configurations")) hbox.addWidget(btn_reset) main_box.addLayout(hbox) # Overlay self.overlay = overlay_widget.OverlayWidget(self) self.overlay.hide() # Effect and animations self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) duration, x = 180, 150 # Animation duration # Animation start # Opacity animation self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity") self.opacity_animation_s.setDuration(duration) self.opacity_animation_s.setStartValue(0.0) self.opacity_animation_s.setEndValue(1.0) # X animation self.x_animation_s = QPropertyAnimation(self, b"geometry") self.x_animation_s.setDuration(duration) self.x_animation_s.setStartValue(QRect(x, 0, parent.width(), parent.height())) self.x_animation_s.setEndValue(QRect(0, 0, parent.width(), parent.height())) # Animation end # Opacity animation self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity") self.opacity_animation_e.setDuration(duration) self.opacity_animation_e.setStartValue(1.0) self.opacity_animation_e.setEndValue(0.0) # X animation self.x_animation_e = QPropertyAnimation(self, b"geometry") self.x_animation_e.setDuration(duration) self.x_animation_e.setStartValue(QRect(0, 0, parent.width(), parent.height())) self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(), parent.height())) # Group animation start self.group_animation_s = QParallelAnimationGroup() self.group_animation_s.addAnimation(self.opacity_animation_s) self.group_animation_s.addAnimation(self.x_animation_s) # Group animation end self.group_animation_e = QParallelAnimationGroup() self.group_animation_e.addAnimation(self.opacity_animation_e) self.group_animation_e.addAnimation(self.x_animation_e) # Connections self.group_animation_e.finished.connect( self._on_group_animation_finished) btn_cancel.clicked.connect(self.close) btn_reset.clicked.connect(self._reset_settings) btn_updates.clicked.connect(self._check_for_updates) # self.thread.finished.connect(self._on_thread_finished) self._combo_font.currentFontChanged.connect( self._change_font) self._combo_font_size.currentTextChanged.connect( self._change_font_size) def __current_line_value_changed(self, value): qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue('highlight_current_line', value) PSetting.HIGHLIGHT_CURRENT_LINE = value def __set_enabled_matching_parenthesis(self, value): qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue("matching_parenthesis", value) PSetting.MATCHING_PARENTHESIS = value def _change_font(self, font): # FIXME: un quilombo esto central = Pireal.get_service("central") mcontainer = central.get_active_db() if mcontainer is not None: query_widget = mcontainer.query_container.currentWidget() if query_widget is not None: weditor = query_widget.get_editor() if weditor is not None: qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) weditor.set_font(font) qs.setValue("font", font) def _change_font_size(self, size): # FIXME: un quilombo esto font = self._combo_font.currentFont() font.setPointSize(int(size)) central = Pireal.get_service("central") mcontainer = central.get_active_db() if mcontainer is not None: query_widget = mcontainer.query_container.currentWidget() if query_widget is not None: weditor = query_widget.get_editor() if weditor is not None: qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) weditor.set_font(font) qs.setValue("font", font) def showEvent(self, event): super(Preferences, self).showEvent(event) self.group_animation_s.start() def resizeEvent(self, event): self.overlay.resize(self.size()) event.accept() def done(self, result): self.res = result self.group_animation_e.start() def _on_group_animation_finished(self): super(Preferences, self).done(self.res) self.settingsClosed.emit() def _check_for_updates(self): # Thread self._thread = QThread() self._updater = updater.Updater() self._updater.moveToThread(self._thread) self._thread.started.connect(self._updater.check_updates) self._updater.finished.connect(self.__on_thread_update_finished) # Show overlay widget self.overlay.show() # Start thread self._thread.start() def __on_thread_update_finished(self): # Hide overlay widget self.overlay.hide() self._thread.quit() msg = QMessageBox(self) if not self._updater.error: if self._updater.version: version = self._updater.version msg.setWindowTitle(self.tr("New version available!")) msg.setText(self.tr("Check the web site to " "download <b>Pireal {}</b>".format( version))) download_btn = msg.addButton(self.tr("Download!"), QMessageBox.YesRole) msg.addButton(self.tr("Cancel"), QMessageBox.RejectRole) msg.exec_() r = msg.clickedButton() if r == download_btn: webbrowser.open_new( "http://centaurialpha.github.io/pireal") else: msg.setWindowTitle(self.tr("Information")) msg.setText(self.tr("Last version installed")) msg.addButton(self.tr("Ok"), QMessageBox.AcceptRole) msg.exec_() else: msg.critical(self, self.tr("Error"), self.tr("Connection error")) self._thread.deleteLater() self._updater.deleteLater() def _reset_settings(self): """ Remove all settings """ msg = QMessageBox(self) msg.setWindowTitle(self.tr("Reset Settings")) msg.setText(self.tr("Are you sure you want to clear all settings?")) msg.setIcon(QMessageBox.Question) msg.addButton(self.tr("No"), QMessageBox.NoRole) yes_btn = msg.addButton(self.tr("Yes"), QMessageBox.YesRole) msg.exec_() r = msg.clickedButton() if r == yes_btn: QSettings(settings.SETTINGS_PATH, QSettings.IniFormat).clear() self.close() def _change_lang(self, index): lang = self._combo_lang.itemText(index) qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue('language', lang)
class Tile(QLabel): moved = pyqtSignal() def __init__(self, parent=None): super(Tile, self).__init__(parent) self.isEmpty = False self.perfectPos = None self.hasPerfectPos = True self.moveEnabled = False def mousePressEvent(self, event): if not self.moveEnabled: return if self.switch(): self.moved.emit() def switch(self, anim=True): var = False for neighbor in self.getNeighbors(): if neighbor.isEmpty: Xself = self.pos().x() Yself = self.pos().y() Xneigh = neighbor.pos().x() Yneigh = neighbor.pos().y() if self.perfectPos.x() == Xneigh and \ self.perfectPos.y() == Yneigh: self.hasPerfectPos = True else: self.hasPerfectPos = False if neighbor.perfectPos.x() == Xself and \ neighbor.perfectPos.y() == Yself: neighbor.hasPerfectPos = True else: neighbor.hasPerfectPos = False if anim: self.animation = QPropertyAnimation(self, "geometry") self.animation.setDuration(200) self.animation.setEndValue(QRect(Xneigh, Yneigh, self.width(), self.height())) self.animation.start() else: self.move(Xneigh, Yneigh) neighbor.move(Xself, Yself) var = True return var def getNeighbors(self): neighbors = [] x = self.pos().x() y = self.pos().y() if self.parent().childAt(x-1, y): neighbors.append(self.parent().childAt(x-1, y)) if self.parent().childAt(x+41, y): neighbors.append(self.parent().childAt(x+41, y)) if self.parent().childAt(x, y-1): neighbors.append(self.parent().childAt(x, y-1)) if self.parent().childAt(x, y+41): neighbors.append(self.parent().childAt(x, y+41)) return neighbors
class MiniMap(QPlainTextEdit): def __init__(self, parent): super(MiniMap, self).__init__(parent) self.setWordWrapMode(QTextOption.NoWrap) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setReadOnly(True) self.setCenterOnScroll(True) self.setMouseTracking(True) self.viewport().setCursor(Qt.PointingHandCursor) self.setTextInteractionFlags(Qt.NoTextInteraction) self._parent = parent self.highlighter = None self.lines_count = 0 if ACTIVATE_OPACITY: self.goe = QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(settings.MINIMAP_MIN_OPACITY) self.animation = QPropertyAnimation(self.goe, b"opacity") self.slider = SliderArea(self) self.slider.show() def __calculate_max(self): line_height = self._parent.cursorRect().height() if line_height > 0: self.lines_count = self._parent.viewport().height() / line_height self.slider.update_position() self.update_visible_area() def set_code(self, source): self.setPlainText(source) self.__calculate_max() def adjust_to_parent(self): self.setFixedHeight(self._parent.height()) self.setFixedWidth(self._parent.width() * settings.SIZE_PROPORTION) x = self._parent.width() - self.width() self.move(x, 0) fontsize = int(self.width() / settings.MARGIN_LINE) if fontsize < 1: fontsize = 1 font = self.document().defaultFont() font.setPointSize(fontsize) self.setFont(font) self.__calculate_max() def update_visible_area(self): if not self.slider.pressed: line_number = self._parent.firstVisibleBlock().blockNumber() block = self.document().findBlockByLineNumber(line_number) cursor = self.textCursor() cursor.setPosition(block.position()) rect = self.cursorRect(cursor) self.setTextCursor(cursor) self.slider.move_slider(rect.y()) def enterEvent(self, event): if ACTIVATE_OPACITY: self.animation.setDuration(300) self.animation.setStartValue(settings.MINIMAP_MIN_OPACITY) self.animation.setEndValue(settings.MINIMAP_MAX_OPACITY) self.animation.start() def leaveEvent(self, event): if ACTIVATE_OPACITY: self.animation.setDuration(300) self.animation.setStartValue(settings.MINIMAP_MAX_OPACITY) self.animation.setEndValue(settings.MINIMAP_MIN_OPACITY) self.animation.start() def mousePressEvent(self, event): super(MiniMap, self).mousePressEvent(event) cursor = self.cursorForPosition(event.pos()) self._parent.jump_to_line(cursor.blockNumber()) def resizeEvent(self, event): super(MiniMap, self).resizeEvent(event) self.slider.update_position() def scroll_area(self, pos_parent, pos_slider): pos_parent.setY(pos_parent.y() - pos_slider.y()) cursor = self.cursorForPosition(pos_parent) self._parent.verticalScrollBar().setValue(cursor.blockNumber()) def wheelEvent(self, event): super(MiniMap, self).wheelEvent(event) self._parent.wheelEvent(event)
class ScreensharingToolbox(base_class, ui_class): exposedPixels = 3 def __init__(self, parent): super(ScreensharingToolbox, self).__init__(parent) with Resources.directory: self.setupUi() parent.installEventFilter(self) self.animation = QPropertyAnimation(self, 'pos') self.animation.setDuration(250) self.animation.setDirection(QPropertyAnimation.Forward) self.animation.setEasingCurve(QEasingCurve.Linear) # or OutCirc with 300ms self.retract_timer = QTimer(self) self.retract_timer.setInterval(3000) self.retract_timer.setSingleShot(True) self.retract_timer.timeout.connect(self.retract) self.resize(self.size().expandedTo(self.toolbox_layout.minimumSize())) def setupUi(self): super(ScreensharingToolbox, self).setupUi(self) # fix the SVG icons, as the generated code loads them as pixmaps, losing their ability to scale -Dan scale_icon = QIcon() scale_icon.addFile(Resources.get('icons/scale.svg'), mode=QIcon.Normal, state=QIcon.Off) viewonly_icon = QIcon() viewonly_icon.addFile(Resources.get('icons/viewonly.svg'), mode=QIcon.Normal, state=QIcon.Off) screenshot_icon = QIcon() screenshot_icon.addFile(Resources.get('icons/screenshot.svg'), mode=QIcon.Normal, state=QIcon.Off) fullscreen_icon = QIcon() fullscreen_icon.addFile(Resources.get('icons/fullscreen.svg'), mode=QIcon.Normal, state=QIcon.Off) fullscreen_icon.addFile(Resources.get('icons/fullscreen-exit.svg'), mode=QIcon.Normal, state=QIcon.On) fullscreen_icon.addFile(Resources.get('icons/fullscreen-exit.svg'), mode=QIcon.Active, state=QIcon.On) fullscreen_icon.addFile(Resources.get('icons/fullscreen-exit.svg'), mode=QIcon.Disabled, state=QIcon.On) fullscreen_icon.addFile(Resources.get('icons/fullscreen-exit.svg'), mode=QIcon.Selected, state=QIcon.On) minimize_icon = QIcon() minimize_icon.addFile(Resources.get('icons/minimize.svg'), mode=QIcon.Normal, state=QIcon.Off) minimize_icon.addFile(Resources.get('icons/minimize-active.svg'), mode=QIcon.Active, state=QIcon.Off) close_icon = QIcon() close_icon.addFile(Resources.get('icons/close.svg'), mode=QIcon.Normal, state=QIcon.Off) close_icon.addFile(Resources.get('icons/close-active.svg'), mode=QIcon.Active, state=QIcon.Off) self.scale_action.setIcon(scale_icon) self.viewonly_action.setIcon(viewonly_icon) self.screenshot_action.setIcon(screenshot_icon) self.fullscreen_action.setIcon(fullscreen_icon) self.minimize_action.setIcon(minimize_icon) self.close_action.setIcon(close_icon) self.scale_button.setIcon(scale_icon) self.viewonly_button.setIcon(viewonly_icon) self.screenshot_button.setIcon(screenshot_icon) self.fullscreen_button.setIcon(fullscreen_icon) self.minimize_button.setIcon(minimize_icon) self.close_button.setIcon(close_icon) self.scale_button.setDefaultAction(self.scale_action) self.viewonly_button.setDefaultAction(self.viewonly_action) self.screenshot_button.setDefaultAction(self.screenshot_action) self.fullscreen_button.setDefaultAction(self.fullscreen_action) self.minimize_button.setDefaultAction(self.minimize_action) self.close_button.setDefaultAction(self.close_action) self.color_depth_button.clear() self.color_depth_button.addItem('Default Color Depth', ServerDefault) self.color_depth_button.addItem('TrueColor (24 bits)', TrueColor) self.color_depth_button.addItem('HighColor (16 bits)', HighColor) self.color_depth_button.addItem('LowColor (8 bits)', LowColor) def eventFilter(self, watched, event): if watched is self.parent() and event.type() == QEvent.Resize: new_x = (watched.width() - self.width()) / 2 self.move(new_x, self.y()) self.animation.setStartValue(QPoint(new_x, -self.height() + self.exposedPixels)) self.animation.setEndValue(QPoint(new_x, 0)) return False def enterEvent(self, event): super(ScreensharingToolbox, self).enterEvent(event) self.retract_timer.stop() self.expose() def leaveEvent(self, event): super(ScreensharingToolbox, self).leaveEvent(event) self.retract_timer.start() def paintEvent(self, event): # make the widget style aware option = QStyleOption() option.initFrom(self) painter = QStylePainter(self) painter.drawPrimitive(QStyle.PE_Widget, option) def expose(self): if self.animation.state() == QPropertyAnimation.Running and self.animation.direction() == QPropertyAnimation.Forward: return elif self.animation.state() == QPropertyAnimation.Stopped and self.pos() == self.animation.endValue(): return self.animation.setDirection(QPropertyAnimation.Forward) self.animation.start() def retract(self): if self.animation.state() == QPropertyAnimation.Running and self.animation.direction() == QPropertyAnimation.Backward: return elif self.animation.state() == QPropertyAnimation.Stopped and self.pos() == self.animation.startValue(): return self.animation.setDirection(QPropertyAnimation.Backward) self.animation.start()
class CoffeeFundWindow(QWidget): signal_back = pyqtSignal() signal_coffee = pyqtSignal() signal_account = pyqtSignal() def __init__(self, parent=None): super().__init__() self.cards = {} # type: Dict[GuiCards, QWidget] """ Python's GC will clean up QPropertyAnimations as soon as it leaves the button handler, therefore they will appear not to work. Use members to store the animations. see http://stackoverflow.com/a/6953965 """ self.slide_in_animation = None self.slide_out_animation = None self.animation_group = None self.setObjectName("coffeeFundWindow") """ Store the position and size of visible/hidden cards for the animation sequences """ self.hidden_geometry = None self.visible_geometry = None layout = QStackedLayout() layout.setStackingMode(QStackedLayout.StackAll) card_remove = RemoveCard() self.cards[GuiCards.RemoveCard] = card_remove layout.addWidget(card_remove) card_choose_action = ChooseActionCard() self.cards[GuiCards.ChooseAction] = card_choose_action layout.addWidget(card_choose_action) card_account = AccountCard() self.cards[GuiCards.AccountInfo] = card_account layout.addWidget(card_account) # keep this as last initialized card, the last card will be shown on startup! card_start = StartCard() self.cards[GuiCards.Start] = card_start layout.addWidget(card_start) self.setLayout(layout) self.setWindowTitle("Kaffeekasse") layout.setCurrentWidget(card_start) self.active_card = None card_choose_action.button_account.clicked.connect(self.signal_account) card_choose_action.button_coffee.clicked.connect(self.signal_coffee) card_account.button_back.clicked.connect(self.signal_back) def set_card_hidden(self, card: QWidget): card.setGeometry(self.hidden_geometry) def show_start(self): self.show_card(GuiCards.Start) def show_account(self, name, value): self.cards[GuiCards.AccountInfo].set_user_name(name) self.cards[GuiCards.AccountInfo].set_balance(value) self.show_card(GuiCards.AccountInfo) def show_choose_action(self, name: str): self.cards[GuiCards.ChooseAction].set_user_name(name) self.show_card(GuiCards.ChooseAction) def show_remove(self): self.show_card(GuiCards.RemoveCard) def show_card(self, card_id: GuiCards): if self.active_card is None: self.active_card = self.cards[GuiCards.Start] if self.active_card == self.cards[card_id]: return if self.visible_geometry is None or self.hidden_geometry is None: self.visible_geometry = self.active_card.geometry() # type: QRect self.hidden_geometry = QRect(self.visible_geometry.x(), self.visible_geometry.height() * 1.5, self.visible_geometry.width(), self.visible_geometry.height()) for key in self.cards.keys(): if key != self.active_card: self.set_card_hidden(self.cards[key]) card_to_show = self.cards[card_id] self.start_card_switch(card_to_show) self.active_card = self.cards[card_id] self.layout().setCurrentWidget(self.active_card) def start_card_switch(self, card_to_show): self.slide_out_animation = QPropertyAnimation(self.active_card, "geometry") self.slide_out_animation.setDuration(ANIMATION_DURATION) self.slide_out_animation.setEasingCurve(QEasingCurve.OutCubic) self.slide_out_animation.setStartValue(self.visible_geometry) self.slide_out_animation.setEndValue(self.hidden_geometry) self.set_card_hidden(card_to_show) self.slide_in_animation = QPropertyAnimation(card_to_show, "geometry") self.slide_in_animation.setDuration(ANIMATION_DURATION) self.slide_in_animation.setEasingCurve(QEasingCurve.InCubic) self.slide_in_animation.setStartValue(self.hidden_geometry) self.slide_in_animation.setEndValue(self.visible_geometry) self.animation_group = QParallelAnimationGroup() self.animation_group.addAnimation(self.slide_out_animation) self.animation_group.addAnimation(self.slide_in_animation) self.animation_group.start()
from PyQt5.QtCore import QPropertyAnimation, QEasingCurve animation = QPropertyAnimation() animation.setTargetObject() animation.setStartValue(0) animation.setEndValue(1000) animation.setDuration(1000) animation.setEasingCurve(QEasingCurve.InOutQuad) animation.start()
class BlueApp: def __init__(self, argv): self.app = QApplication(argv) self.mainWindow = QtWidgets.QMainWindow() self.mainWindow.closeEvent = self.onClose self.ui = blueMainUi.Ui_MainWindow() self.ui.setupUi(self.mainWindow) #settings and statistics self.defaultSettings = dict(image_detect=True, text_detect=True, game_type=0, pipeRank=0, goal = 10, startDate = time.time(), avata = "res/icon.png", name = "窜天猴") self.defaultStat = dict(stat = [ [0, 0, 0, 0] for i in range(7)], achivement = 0, lastWater = 0, lastFertilize = 0, cleanHours = 0, cleanMinutes = 0) self.achivementsList = ["大淫魔", "从头开始", "欲火渐盛", "钢筋铁骨", "渐入佳境","心无杂念"] self.achivementsStd = [0, 24, 24 * 3, 24 * 7, 24 * 31, 27 * 365] self.loadSettings() self.validateSettings() self.loadStatistics() #setup the visibles self.setupUi2() self.setupWidget1() self.setupWidget2() self.setupWidget3() self.setupWidget4() self.refreshStatistics() #setup porn_detector self.devMode = False self.timeToExit = False self.pornDectector = porn_detector_final.PornDetector() self.pornDetected = False self.detectThread = threading.Thread(target = self.detectPorn) self.detectThread.start() self.alarm = False #first alarm, then take action #setup timer self.cleanMinute = 0 self.MinuteTimer = QTimer() self.MinuteTimer.setInterval(1000 * 60) self.MinuteTimer.timeout.connect(self.addCleanMinute) self.MinuteTimer.start() #lauch self.mainWindow.show() self.connections() def addCleanMinute(self): self.stat["cleanMinutes"] += 1 if self.stat["cleanMinutes"] == 60: self.self.stat["cleanMinutes"] = 0 self.stat["cleanHours"] += 1 self.saveStatistics() self.refreshStatistics() self.checkLevel() def call_zqz(self): if self.settings["game_type"] == 0: os.system("python2 easy_maze/PyMaze.py") else : os.system("python2 esay_game/play.py") QtWidgets.QMessageBox.information(None, "bluer", "你有10s的时间关掉黄黄的东西。") time.sleep(10) def detectPorn(self): while(True): if "PORN_DETECTED" == self.pornDectector.porn_detector(self.settings["image_detect"], self.settings["text_detect"], self.devMode): if self.alarm: self.call_zqz() self.stat["cleanHours"] -= 24 if self.stat["cleanHours"] < 0: self.stat["cleanHours"] = 0 l = self.stat["stat"][time.localtime(time.time())[6]] h = time.localtime(time.time())[3] if h >= 0 and h < 6: l[0] = 1 elif h >= 6 and h < 12: l[1] = 1 elif h >= 12 and h < 18: l[2] = 1; else: l[3] = 1; else: self.alarm = True else: self.alarm = True self.saveStatistics() self.refreshStatistics() time.sleep(10) def onClose(self, event): self.mainWindow.hide() event.ignore() def onTrayClicked(self, event): if event == QSystemTrayIcon.Trigger or event == QSystemTrayIcon.DoubleClick: self.mainWindow.show() def saveSettings(self, event): QtWidgets.QMessageBox.Question = QIcon("res/logo-tray.png") if self.settings["goal"] != self.ui.spin_goal.value(): ret = QtWidgets.QMessageBox.question(self.mainWindow, "Blue", "确定要将目标改为" + str(self.ui.spin_goal.value()) + "天吗?\n" "此操作会重置当前任务的进度。") if ret != QtWidgets.QMessageBox.No: self.settings["goal"] = self.ui.spin_goal.value() self.saveStatistics() self.refreshStatistics() QtWidgets.QMessageBox.information(None, "Blue", "新目标设置为" + str(self.settings["goal"]) + "天") else: QtWidgets.QMessageBox.information(None, "Blue", "目标没有被重置") try: sfile = open(PATH_TO_SETTINGS, "w") json.dump(self.settings, sfile) sfile.close() except Exception: return QtWidgets.QMessageBox.information(None, "Blue", "设置已保存:D") self.refreshStatistics() def checkLevel(self): for i in range(5, -1, -1): if self.stat["cleanHours"] >= self.achivementsStd[i] and self.stat["achivement"] < i: QtWidgets.QMessageBox.information(None, "Blue", "等级提升为Lv. " + str(i) + " :" + self.achivementsList[i]) self.stat["achivement"] = i self.saveStatistics() break def saveStatistics(self): json.dump(self.stat, open(PATH_TO_STATISTICS, "w")) def refreshStatistics(self): days = time.localtime(time.time()) delta = self.settings["goal"] - self.stat["cleanHours"] if delta == 0: QtWidgets.QMessageBox.information(None, "Blue", "目标达成!!!\n请设置新的目标!!!") self.slideClicked3(None) self.ui.lb_days.setText(str(delta)) self.ui.lb_goal.setText(str(self.settings["goal"])) self.ui.lb_achv.setText(self.achivementsList[self.stat["achivement"]]) self.ui.lb_lv.setText("Lv. " + str(self.stat["achivement"])) self.ui.lb_growth.setText(str(self.stat["cleanHours"] // 24)) #setup the water and ferilization if days[7] == time.localtime(self.stat["lastWater"])[7]: self.ui.lb_jiaoshui.setPixmap(QPixmap("res/ack.png")) self.watered = True else: self.watered = False if days[7] == time.localtime(self.stat["lastFertilize"])[7]: self.ui.lb_shifei.setPixmap(QPixmap("res/ack.png")) self.fertilized = True else: self.fertilized = False #setup the calendar pixmapA = QPixmap("res/lu.png") pixmapB = QPixmap("res/blue.png") h = days[3] if h >= 0 and h < 6: r = 0 elif h >= 6 and h < 12: r = 1 elif h >= 12 and h < 18: r = 2 else: r = 3 for i in range(days[6]): for j in range(4): if self.stat["stat"][i][j] == 0: self.statLabels[i][j].setPixmap(pixmapA) else: self.statLabels[i][j].setPixmap(pixmapB) day = days[6] for j in range(r): if self.stat["stat"][day][j] == 0: self.statLabels[day][j].setPixmap(pixmapA) else: self.statLabels[day][j].setPixmap(pixmapB) #setup the wall for i in range(6): self.achivIcons[i].setPixmap(QPixmap("res/" + str(i) * 2)) for i in range(self.stat["achivement"] + 1): self.achivIcons[i].setPixmap(QPixmap("res/" + str(i))) def loadSettings(self): try: sfile = open(PATH_TO_SETTINGS, "r") self.settings = json.load(sfile) sfile.close() except: self.settings = self.defaultSettings self.saveSettings(None) def validateSettings(self): for keys in self.defaultSettings: try: self.settings[keys] except: self.settings[keys] = self.defaultSettings[keys] def loadStatistics(self): try: sfile = open(PATH_TO_STATISTICS, "r") self.stat = json.load(sfile) except: self.stat = self.defaultStat for keys in self.defaultStat: try: self.stat[keys] except: self.stat[keys] = self.defaultStat[keys] self.saveStatistics() def refreshInfo(self): #setup avata pixmap = QPixmap() pixmap.load("res/avata_mask") pixmap.scaled(115, 115) self.ui.lb_avata.setMask(pixmap.mask()) pixmap.load(self.settings["avata"]) self.ui.lb_avata.setPixmap(pixmap) # self.ui.lb_avata2.setMask(pixmap.mask()) # pixmap.load(self.settings["avata"]) # self.ui.lb_avata2.setPixmap(pixmap) #setup the name self.ui.lb_welcomname.setText(self.settings["name"]) self.ui.lb_nick.setText(self.settings["name"]) def appExit(self, event): if self.devMode == False: QtWidgets.QMessageBox.information(None, "bluer", "开发者模式开启") self.devMode = True else: QtWidgets.QMessageBox.information(None, "bluer", "开发者模式关闭") self.devMode = False def avataEdit(self, event): openDlg = QtWidgets.QFontDialog() openDlg.open() def setupUi2(self): #setup event handling self.sideButtons = [self.ui.lb1, self.ui.lb2, self.ui.lb3, self.ui.lb4] self.ui.lb_exit.mousePressEvent = self.appExit self.setupAnimes() self.setupSideButtons() self.refreshInfo() #setup tray self.icon = QIcon("res/logo-tray.png") self.trayIcon = QSystemTrayIcon() self.trayIcon.setIcon(self.icon) self.trayIcon.activated.connect(self.onTrayClicked) self.trayIcon.show() #setup the info edit self.ui.lb_avata.mousePressEvent = self.avataEdit def setupAnimes(self): self.shiftAnime1 = QPropertyAnimation() self.shiftAnime1.setTargetObject(self.ui.widget1) self.shiftAnime1.setPropertyName("geometry".encode()) self.shiftAnime1.setDuration(400) self.shiftAnime1.setStartValue(QRect(177, 29, 0, 571)) self.shiftAnime1.setEndValue(QRect(177, 29, 623, 571)) self.shiftAnime2 = QPropertyAnimation() self.shiftAnime2.setTargetObject(self.ui.widget2) self.shiftAnime2.setPropertyName("geometry".encode()) self.shiftAnime2.setDuration(400) self.shiftAnime2.setStartValue(QRect(800, 29, 0, 571)) self.shiftAnime2.setEndValue(QRect(177, 29, 623, 571)) self.shiftAnime3 = QPropertyAnimation() self.shiftAnime3.setTargetObject(self.ui.widget3) self.shiftAnime3.setPropertyName("geometry".encode()) self.shiftAnime3.setDuration(400) self.shiftAnime3.setStartValue(QRect(800, 29, 623, 571)) self.shiftAnime3.setEndValue(QRect(177, 29, 623, 571)) self.shiftAnime4 = QPropertyAnimation() self.shiftAnime4.setTargetObject(self.ui.widget4) self.shiftAnime4.setPropertyName("geometry".encode()) self.shiftAnime4.setDuration(400) self.shiftAnime4.setStartValue(QRect(800, 29, 623, 571)) self.shiftAnime4.setEndValue(QRect(177, 29, 623, 571)) self.selectedWidget = self.ui.widget1 def setSlideMid(self, bt): if self.selectedSideButton != bt: bt.setStyleSheet(slide_bt_mid) def setSlideUp(self, bt): if self.selectedSideButton != bt: bt.setStyleSheet(slide_bt_up) def setSlideDown(self, bt): self.selectedSideButton.setStyleSheet(slide_bt_up) self.selectedSideButton = bt bt.setStyleSheet(slide_bt_down) def slideEnter1(self, event): self.setSlideMid(self.ui.lb1) def slideEnter2(self, event): self.setSlideMid(self.ui.lb2) def slideEnter3(self, event): self.setSlideMid(self.ui.lb3) def slideEnter4(self, event): self.setSlideMid(self.ui.lb4) def slideLeave1(self, event): self.setSlideUp(self.ui.lb1) def slideLeave2(self, event): self.setSlideUp(self.ui.lb2) def slideLeave3(self, event): self.setSlideUp(self.ui.lb3) def slideLeave4(self, event): self.setSlideUp(self.ui.lb4) def slideBack(self, event): self.setSlideDown(self.ui.lb1) self.ui.widget1.raise_() self.shiftAnime1.start() self.selectedWidget = self.ui.widget1 def slideClicked1(self, event): self.setSlideDown(self.ui.lb1) if self.selectedWidget != self.ui.widget1: self.ui.widget1.raise_() self.shiftAnime1.start() self.selectedWidget = self.ui.widget1 def slideClicked2(self, event): self.setSlideDown(self.ui.lb2) if self.selectedWidget != self.ui.widget2: self.ui.widget2.raise_() self.shiftAnime2.start() self.selectedWidget = self.ui.widget2 def slideClicked3(self, event): self.setSlideDown(self.ui.lb3) if self.selectedWidget != self.ui.widget3: self.ui.widget3.raise_() self.shiftAnime3.start() self.selectedWidget = self.ui.widget3 def jiaoshuiCheck(self, event): pixmap = QPixmap() pixmap.load("res/ack.png") self.ui.lb_jiaoshui.setPixmap(pixmap) self.stat["lastWater"] = time.time() self.saveStatistics() def shifeiCheck(self, event): pixmap = QPixmap() pixmap.load("res/ack.png") self.ui.lb_shifei.setPixmap(pixmap) self.stat["lastFertilize"] = time.time() self.saveStatistics() def slideClicked4(self, event): self.setSlideDown(self.ui.lb4) if self.selectedWidget != self.ui.widget4: self.ui.widget4.raise_() self.shiftAnime4.start() self.selectedWidget = self.ui.widget4 def setupWidget1(self): #setup the tree movie = QMovie() movie.setFileName("res/tree.gif") self.ui.lb_tree.setMovie(movie) self.ui.lb_tree_big.setMovie(movie) movie.start() #setup the statistics self.ui.gridLayout.setHorizontalSpacing(60) self.ui.gridLayout.setVerticalSpacing(10) self.ui.gridLayout.setGeometry(QRect(0, 51, 291, 224)) self.ui.gridLayout.setAlignment(QtCore.Qt.AlignCenter) self.statLabels = [] for i in range(7): self.statLabels.append([]) for j in range(4): self.statLabels[i].append(QLabel()) self.statLabels[i][j].setScaledContents(True) self.statLabels[i][j].setAutoFillBackground(False) self.statLabels[i][j].setAlignment(QtCore.Qt.AlignCenter) self.ui.gridLayout.addWidget(self.statLabels[i][j], i, j, 1, 1) def setupWidget2(self): self.ui.lb_jiaoshui.mousePressEvent = self.jiaoshuiCheck self.ui.lb_shifei.mousePressEvent = self.shifeiCheck def setupWidget3(self): self.ui.check_maze.mousePressEvent = self.mazeCliked self.ui.check_paper.mousePressEvent = self.paperCliked self.ui.check_pic.mousePressEvent = self.picCliked self.ui.check_text.mousePressEvent = self.textClicked self.ui.lb_save.mousePressEvent = self.saveSettings self.ui.spin_goal.setValue(self.settings["goal"]) if self.settings["game_type"] == 0: self.mazeCliked(None) else: self.paperCliked(None) self.picCliked(None) self.picCliked(None) self.textClicked(None) self.textClicked(None) def setupWidget4(self): self.achivIcons = [self.ui.lb_a0, self.ui.lb_a1, self.ui.lb_a2, self.ui.lb_a3, self.ui.lb_a4, self.ui.lb_a5] for i in range(6): self.achivIcons[i].setPixmap(QPixmap("res/" + str(i) * 2)) def mazeCliked(self, event): pixmap = QPixmap() pixmap.load("res/checked.png") self.ui.check_maze.setPixmap(pixmap) pixmap.load("res/unchecked.png") self.ui.check_paper.setPixmap(pixmap) self.settings["game_type"] = 0 def paperCliked(self, event): pixmap = QPixmap() pixmap.load("res/checked.png") self.ui.check_paper.setPixmap(pixmap) pixmap.load("res/unchecked.png") self.ui.check_maze.setPixmap(pixmap) self.settings["game_type"] = 1 def picCliked(self, event): pixmap = QPixmap() pixmap.load("res/checked.png") self.ui.check_pic.setPixmap(pixmap) pixmap.load("res/unchecked.png") self.ui.check_text.setPixmap(pixmap) self.settings["pic_detect"] = 1 self.settings["text_detect"] = 0 def textClicked(self, event): pixmap = QPixmap() pixmap.load("res/checked.png") self.ui.check_text.setPixmap(pixmap) pixmap.load("res/unchecked.png") self.ui.check_pic.setPixmap(pixmap) self.settings["pic_detect"] = 1 self.settings["text_detect"] = 1 def setupSideButtons(self): self.ui.lb1.enterEvent = self.slideEnter1 self.ui.lb1.leaveEvent = self.slideLeave1 self.ui.lb1.mousePressEvent = self.slideClicked1 self.ui.lb2.enterEvent = self.slideEnter2 self.ui.lb2.leaveEvent = self.slideLeave2 self.ui.lb2.mousePressEvent = self.slideClicked2 self.ui.lb3.enterEvent = self.slideEnter3 self.ui.lb3.leaveEvent = self.slideLeave3 self.ui.lb3.mousePressEvent = self.slideClicked3 self.ui.lb4.enterEvent = self.slideEnter4 self.ui.lb4.leaveEvent = self.slideLeave4 self.ui.lb4.mousePressEvent = self.slideClicked4 self.ui.lb4.enterEvent = self.slideEnter4 self.ui.lb4.leaveEvent = self.slideLeave4 self.ui.lb4.mousePressEvent = self.slideClicked4 self.ui.lb_back2.mousePressEvent = self.slideBack self.ui.lb_back3.mousePressEvent = self.slideBack self.ui.lb_back4.mousePressEvent = self.slideBack for lb in self.sideButtons: lb.setStyleSheet(slide_bt_up) self.selectedSideButton = self.ui.lb1 self.slideClicked1(None) def connections(self): pass
class CoolToolButton(QToolButton): def __init__(self, action=None, parent=None): super().__init__(parent) self._fader = 0 if action is not None: self.setDefaultAction(action) self.setAttribute(Qt.WA_Hover, True) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) def _set_fader(self, value): self._fader = value self.update() def _get_fader(self): return self._fader fader = pyqtProperty(float, fget=_get_fader, fset=_set_fader) def event(self, event): if event.type() == QEvent.Enter: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(150) self.anim.setEndValue(1.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) elif event.type() == QEvent.Leave: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(124) self.anim.setEndValue(0.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) else: return QToolButton.event(self, event) return False def paintEvent(self, event): painter = QPainter(self) if self.isEnabled() and not self.isDown() and not self.isChecked(): painter.save() hover_color = QColor("#424242") faded_hover_color = QColor(hover_color) faded_hover_color.setAlpha(int(self._fader * hover_color.alpha())) painter.fillRect(event.rect(), faded_hover_color) painter.restore() elif self.isDown() or self.isChecked(): painter.save() selected_color = QColor("#161719") painter.fillRect(event.rect(), selected_color) painter.restore() is_titled = bool(self.defaultAction().property("titled")) icon_rect = QRect(0, 0, 32, 32) icon_rect.moveCenter(event.rect().center()) if is_titled: font = painter.font() center_rect = event.rect() font.setPointSizeF(6) fm = QFontMetrics(font) line_height = fm.height() text_flags = Qt.AlignHCenter | Qt.AlignTop project_name = self.defaultAction().property("heading") if project_name is not None: center_rect.adjust(0, line_height, 0, 0) icon_rect.moveTop(center_rect.top()) else: icon_rect.moveCenter(center_rect.center()) self.icon().paint(painter, icon_rect, Qt.AlignCenter) painter.setFont(font) r = QRect(0, 5, self.rect().width(), line_height) painter.setPen(Qt.white) margin = 5 available_width = r.width() - margin ellided_project_name = fm.elidedText( project_name, Qt.ElideMiddle, available_width) painter.drawText(r, text_flags, ellided_project_name) else: self.icon().paint(painter, icon_rect, Qt.AlignCenter) def sizeHint(self): button_size = self.iconSize().expandedTo(QSize(48, 48)) return button_size def minimumSizeHint(self): return QSize(8, 8)
class FancyButton(QToolButton): def __init__(self, text="", parent=None): super().__init__(parent) self.setAttribute(Qt.WA_Hover, True) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) if text: self.setText(text) self._fader = 0 def _set_fader(self, value): self._fader = value self.update() def _get_fader(self): return self._fader fader = pyqtProperty(float, fget=_get_fader, fset=_set_fader) def event(self, event): if event.type() == QEvent.Enter: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(150) self.anim.setEndValue(1.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) elif event.type() == QEvent.Leave: self.anim = QPropertyAnimation(self, b"fader") self.anim.setDuration(124) self.anim.setEndValue(0.0) self.anim.start(QPropertyAnimation.DeleteWhenStopped) else: return QToolButton.event(self, event) return False def paintEvent(self, event): painter = QPainter(self) if self.isEnabled() and not self.isDown() and not self.isChecked(): painter.save() hover_color = QColor("#424242") faded_hover_color = QColor(hover_color) faded_hover_color.setAlpha(int(self._fader * hover_color.alpha())) painter.fillRect(event.rect(), faded_hover_color) painter.restore() elif self.isDown() or self.isChecked(): painter.save() selected_color = QColor("#090909") painter.fillRect(event.rect(), selected_color) painter.restore() # fm = QFontMetrics(painter.font()) # rect = QRect(-3, 2, self.rect().width(), fm.height()) rect = event.rect() icon_rect = QRect(0, 0, 22, 22) self.icon().paint(painter, icon_rect, Qt.AlignVCenter) painter.drawText( rect.adjusted(0, 0, -3, 0), Qt.AlignRight | Qt.AlignVCenter, self.text()) def sizeHint(self): self.ensurePolished() s = self.fontMetrics().size(Qt.TextSingleLine, self.text()) s.setWidth(s.width() + 25) return s.expandedTo(QApplication.globalStrut())