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)
def mouseReleaseEvent(self, event): 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 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 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 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
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()
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())
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 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 shake_screen(self) -> None: a = QPropertyAnimation(self._stack, b'pos') a.setEasingCurve(QEasingCurve.InOutSine) a.setDuration(500) for step, offset in enumerate([0, 1, -2, 2, -1, 0]): a.setKeyValueAt(step * 0.2, self._stack.pos() + QPoint(offset * 40, 0)) a.start(QPropertyAnimation.DeleteWhenStopped) self._shakeanim = a
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 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 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 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 AnimatedButton(QToolButton): def __init__(self, on_tick_func, anim_start=0, anim_end=255, anim_duration=300, parent=None): super().__init__(parent=parent) self._opacity = 0 self.anim_start = anim_start self.anim_end = anim_end self.anim_duration = anim_duration self.anim = QPropertyAnimation(self, b'opacity') self.anim.setDuration(anim_duration) self.anim.setStartValue(anim_start) self.anim.setEndValue(anim_end) self.on_tick = on_tick_func def set_anim_start(self, val): self.anim_start = val self.anim.setStartValue(val) def set_anim_end(self, val): self.anim_end = val self.anim.setEndValue(val) def set_anim_duration(self, val): self.anim_duration = val self.anim.setDuration(val) def get_opacity(self): return self._opacity def set_opacity(self, value): self._opacity = value if value != 1: self.on_tick(self, value) opacity = pyqtProperty('int', get_opacity, set_opacity) def enterEvent(self, event): self.anim.stop() self.anim.setStartValue(self.anim.currentValue()) self.anim.setEndValue(self.anim_end) self.anim.start() super().enterEvent(event) def leaveEvent(self, event): self.anim.stop() self.anim.setStartValue(self.anim.currentValue()) self.anim.setEndValue(self.anim_start) self.anim.start() super().leaveEvent(event)
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)
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 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)
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 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 move(self, car, px, py): animation = QPropertyAnimation(self, b'pos') animation.setParent(self) animation.setDuration(2000) animation.setTargetObject(car) animation.setStartValue(QPoint(100, 100)) animation.setEndValue(QPoint(100, 400)) animation.setLoopCount(1) # self.animation.finished.connect(self.animationFinished) animation.start()
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 _perform_move(self, a, pos): from PyQt5.QtCore import QPropertyAnimation # create animation for this move operation anim = QPropertyAnimation(a, b'pos') anim.setDuration(200) anim.setEndValue(pos) anim.start() # the QPropertyAnimation object must outlive this method, so we attach it to this instance # TODO we should really collect it afterwards, perhaps with a handler for the finished() signal... self.animations.append(anim)
class StdInfo(QLabel): def __init__(self, text_func, align=Qt.AlignRight | Qt.AlignBottom, parent=None, font=None, **kwds): QLabel.__init__(self, parent, **kwds) if font == None: font = QFont() font.setPointSize(36) self.setStyleSheet("QLabel {color: gray;}") self.setFont(font) self.text_func = text_func self.align = align if callable(text_func): self.display = self.display_func else: self.setText(self.text_func) self.display = self.display_str effect = QGraphicsOpacityEffect(self) self.setGraphicsEffect(effect) self.anim = QPropertyAnimation(effect, b"opacity") self.anim.setDuration(2000) self.anim.setStartValue(1.) self.anim.setEndValue(0.) # self.anim.setEasingCurve(QEasingCurve.OutQuad) self.anim.finished.connect(self.hide) self.parent().resized.connect(self.set_position) def set_position(self, pos=None): if pos == None: coords = self.parent().geometry().getCoords() if self.align & Qt.AlignLeft: x = coords[0] else: x = coords[2] - self.width() if self.align & Qt.AlignTop: y = coords[1] else: y = coords[3] - self.height() pos = (x, y) self.move(*pos) def display_func(self): self.setText(self.text_func()) self.show() self.anim.stop() self.anim.start() def display_str(self): self.show() # self.anim.updateCurrentValue(1.) self.anim.stop() self.anim.start()
class MessageTip(QWidget): def __init__(self, msg: str): super().__init__() self.initUI(msg) def initUI(self, msg: str): self.setGeometry(300, 300, 350, 120) self.setStyleSheet("background-color: blue") self.setWindowFlags(Qt.FramelessWindowHint) layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) label = QLabel() label.setText(msg) layout.addWidget(label) self.setLayout(layout) self.desktop = QDesktopWidget() self.move((self.desktop.availableGeometry().width() - self.width()), self.desktop.availableGeometry().height()) #初始化位置到右下角 self.showAnimation() def showAnimation(self): #显示弹出框动画 self.animation = QPropertyAnimation(self, b'pos') self.animation.setDuration(500) self.animation.setStartValue(QPoint(self.x(), self.y())) self.animation.setEndValue( QPoint( (self.desktop.availableGeometry().width() - self.width()), (self.desktop.availableGeometry().height() - self.height()))) self.animation.start() #设置弹出框1秒弹出,然后渐隐 self.remainTimer = QTimer() self.remainTimer.timeout.connect(self.closeAnimation) self.remainTimer.start(1000) #定时器3秒 def closeAnimation(self): #清除Timer和信号槽 self.remainTimer.stop() #self.disconnect(self.remainTimer,SLOT("closeAnimation()")) self.remainTimer.timeout.disconnect(self.closeAnimation) self.remainTimer.deleteLater() self.remainTimer = None #弹出框渐隐 self.animation = QPropertyAnimation(self, b"windowOpacity") self.animation.setDuration(1000) self.animation.setStartValue(1) self.animation.setEndValue(0) self.animation.start() #动画完成后清理 #self.connect(self.animation,SIGNAL("finished()"),SLOT("clearAll()")) self.animation.finished.connect(self.clearAll) def clearAll(self): self.close()
class PushButtonFont(QPushButton): LoadingText = "\uf110" def __init__(self, *args, **kwargs): super(PushButtonFont, self).__init__(*args, **kwargs) self.fontSize = self.font().pointSize() * 2 self._rotateAnimationStarted = False self._rotateAnimation = QPropertyAnimation(self) self._rotateAnimation.setTargetObject(self) self._rotateAnimation.setStartValue(1) self._rotateAnimation.setEndValue(12) self._rotateAnimation.setDuration(1000) self._rotateAnimation.setLoopCount(-1) # 无限循环 self._rotateAnimation.valueChanged.connect(self.update) self.clicked.connect(self._onClick) def paintEvent(self, _): option = QStyleOptionButton() self.initStyleOption(option) painter = QStylePainter(self) if self._rotateAnimationStarted: option.text = "" painter.drawControl(QStyle.CE_PushButton, option) if not self._rotateAnimationStarted: return painter.save() font = self.font() font.setPointSize(self.fontSize) font.setFamily("FontAwesome") painter.setFont(font) # 变换坐标为正中间 painter.translate(self.rect().center()) # 旋转90度 painter.rotate(self._rotateAnimation.currentValue() * 30) fm = self.fontMetrics() # 在变换坐标后的正中间画文字 w = fm.width(self.LoadingText) h = fm.height() painter.drawText( QRectF(0 - w * 2, 0 - h, w * 2 * 2, h * 2), Qt.AlignCenter, self.LoadingText) painter.restore() def _onClick(self): if self._rotateAnimationStarted: self._rotateAnimationStarted = False self._rotateAnimation.stop() return self._rotateAnimationStarted = True self._rotateAnimation.start() def update(self, _=None): super(PushButtonFont, self).update()
def fadeIn(self): g = QGraphicsOpacityEffect(self) self.errorWidget.setGraphicsEffect(g) a = QPropertyAnimation(g, self.animationProp, self) a.setDuration(350) a.setStartValue(0) a.setEndValue(1) a.setEasingCurve(QEasingCurve.InBack) #a.valueChanged.connect(lambda:self.errorWidget.show()) self.errorWidget.show() a.start()
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('resource\\images\\menu\\保存为播放列表.png'), '保存为播放列表', self) self.clearPlayListAct = QAction( QIcon('resource\\images\\menu\\清空正在播放_16_16.png'), '清空"正在播放"', self) if self.actionFlag: self.showPlayListAct = QAction( QIcon('resource\\images\\menu\\显示正在播放列表.png'), '显示正在播放列表', self) self.fillScreenAct = QAction( QIcon('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)
class Window(QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.setupUi(self) self.outani = QPropertyAnimation(self.widget, b"geometry") # 背后隐藏的控件 self.outani.setDuration(1000) # 1s self.outani.setEndValue(QRect(0, 30, 178, 681)) # 只是x坐标变化 # 移进去动画 self.inani = QPropertyAnimation(self.widget, b"geometry") # 背后隐藏的控件 self.inani.setDuration(1000) # 1s self.inani.setEndValue(QRect(0, -580, 178, 681)) self.inani.finished.connect(self.onFinish) # 绑定打开关闭事件 self.openButton.clicked.connect(self.onOpen) self.closeButton.clicked.connect(self.onClose) #打开文件 self.action.triggered.connect(self.openFile) self.action.setStatusTip('导入矩阵') self.action.setShortcut('Ctrl+Q') #退出系统 self.action_2.triggered.connect(self.close) self.action_2.setStatusTip('退出系统') self.action_2.setShortcut('Ctrl+E') #开发者信息 self.action_3.setStatusTip('唐伟泽 谢家柯 2016.12.3') def onOpen(self): # 设置按钮不可见 self.openButton.setVisible(False) self.widget.setVisible(True) # 背后的待拉出来的控件可见 self.graphicsView.setGeometry(QtCore.QRect(195, 1, 611, 641)) self.outani.start() # 开启动画效果 def onClose(self): self.outani.stop() # 如果移动到一半则停止 self.inani.start() # 退回去 def onFinish(self): # 关闭动画结束 self.widget.setVisible(False) self.openButton.setVisible(True) self.graphicsView.setGeometry(QtCore.QRect(0, 0, 801, 641)) def openFile(self): fileName1, filetype = QFileDialog.getOpenFileName( self, "选取文件", "/Users/Kelisiya/Desktop", "All Files (*);;Text Files (*.txt)") print(fileName1, filetype)
def unfade(self, widget): if (self.key != 'js83judu4fuiy'): self.effect = QGraphicsOpacityEffect() widget.setGraphicsEffect(self.effect) animation = QPropertyAnimation(self.effect, b"opacity") animation.setDuration(3000) animation.setStartValue(0) animation.setEndValue(1) animation.start() self.animations.append(animation) else: exit('BUY IT!')
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 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()
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 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 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 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 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 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())
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
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()