def __init__(self): super(Surface, self).__init__() self.resize(800, 600) # 增加两个tab的widget side_cover_widget = QWidget() center_cover_widget = QWidget() # 四周弹窗的布局 side_layout = QGridLayout() left = QPushButton('左', clicked=self.left_open) top = QPushButton('上', clicked=self.top_open) right = QPushButton('右', clicked=self.right_open) bottom = QPushButton('下', clicked=self.bottom_open) side_layout.addWidget(left, 1, 0) side_layout.addWidget(top, 0, 1) side_layout.addWidget(right, 1, 2) side_layout.addWidget(bottom, 2, 1) side_cover_widget.setLayout(side_layout) # 中心弹窗的布局 center_layout = QHBoxLayout() center = QPushButton('中心', clicked=self.center_open) center_layout.addWidget(center, alignment=Qt.AlignCenter) center_cover_widget.setLayout(center_layout) # 加入主窗口 self.addTab(side_cover_widget, '四周弹出') self.addTab(center_cover_widget, '中心弹出') # 中心弹窗遮罩体 opacity = QGraphicsOpacityEffect() opacity.setOpacity(0.4) self.cover = QWidget(self) self.cover.setGraphicsEffect(opacity) self.cover.setStyleSheet("background-color: rgb(150,150,150);") self.cover.setAutoFillBackground(True) self.cover.resize(self.width(), self.height()) self.cover.hide()
def __init__(self): super(QDialog, self).__init__() self.layout = QGridLayout(self) # QVBoxLayout(self) # Button properties reopen_button = QPushButton("M") reopen_button.setGeometry(0, 0, 100, 100) reopen_button.setStatusTip("Afficher le menu en plein écran") reopen_button.clicked.connect(self.accept) reopen_button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) reopen_button.setStyleSheet("background-color:rgba(55,55,55,15);") reopen_button.setFont(QFont("Times", 48)) self.setGeometry(0, 0, 150, 150) # Position on screen dialog_size = self.geometry().getRect() desktop_size = QApplication.desktop().screenGeometry().getRect() *_, x, y = map(lambda x, y: y - x - 30, dialog_size, desktop_size) self.move(x, y) # Add trnasparency self.layout.addWidget(reopen_button) op = QGraphicsOpacityEffect(self) op.setOpacity(0.5) # 0 to 1 will cause the fade effect to kick in self.setGraphicsEffect(op) self.setAutoFillBackground(True) self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(Qt.FramelessWindowHint)
class Label(QLabel): def __init__(self, data=None, parent=None): super(Label, self).__init__(parent) self.opacity = QGraphicsOpacityEffect() self.opacityInfo(data) self.setEffects() def opacityInfo(self, data): if 'label_opacity' in data: self.label_opacity = data['label_opacity'] self.touch_opacity = data['touch_opacity'] else: self.label_opacity = 0.9 self.touch_opacity = 0.65 def enterEvent(self, event): self.changeEffects() def leaveEvent(self, event): self.setEffects() def setEffects(self): self.changeOpacity(self.label_opacity) def changeEffects(self): self.changeOpacity(self.touch_opacity) def changeOpacity(self, data): self.opacity.setOpacity(data) self.setGraphicsEffect(self.opacity)
def init_ui(self): self.setMinimumWidth(320) self.setMinimumHeight(240) layout = QBoxLayout(QBoxLayout.LeftToRight) self.setLayout(layout) lb_1 = QLabel() self.origin_pixmap = self.origin_pixmap.scaledToHeight(240) # 사이즈가 조정 lb_1.setPixmap(self.origin_pixmap) layout.addWidget(lb_1) # 자를 영역 선택, 복사 rect = QRect(50, 50, 50, 50) cropped = self.origin_pixmap.copy(rect) self.lb_2 = QLabel() self.lb_2.setPixmap(cropped) self.lb_2.setFixedSize(100, 100) layout.addWidget(self.lb_2) w = Rectangle(parent=lb_1) w.setGeometry(0, 0, 100, 100) w.setStyleSheet("background-color: red") opacity_effect = QGraphicsOpacityEffect(self) opacity_effect.setOpacity(0.3) w.setGraphicsEffect(opacity_effect) w.change_position.connect(self.crop_image)
def checkResults(self): """ 登录 后 查询成绩 对应的是widget_2 :return: """ # tab # self.horizontalLayout_2.setStretchFactor(self.ScoreTableWidget, 1) self.ScoreTableWidget.show() ani = QPropertyAnimation(self.ScoreTableWidget, b'geometry', self) ani.setDuration(2000) # ani.setEasingCurve(QEasingCurve.InQuint) ani.setStartValue( QRect(self.widget.pos().x() + self.widget.width(), self.ScoreTableWidget.pos().y(), 0, self.height())) ani.setEndValue( QRect(self.widget.pos().x() + self.widget.width(), self.ScoreTableWidget.pos().y(), self.width() - self.widget.width(), self.height())) ani.start() ani.finished.connect( lambda: self.horizontalLayout_3.addWidget(self.ScoreTableWidget)) ani.finished.connect( lambda: self.removeSpacer(self.horizontalLayout_2)) e = QGraphicsOpacityEffect() e.setOpacity(0.6) t = QTimer() self.ScoreTableWidget.setGraphicsEffect(e)
class DummyButton(QPushButton): def __init__(self, value, max, parent=None): super().__init__(str(value), parent) self.setFont(QFont("Consolas", 16, 3)) self.setFixedSize(100, 50) self.done = False self.index = value self.max = max self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) self.fade_anim = QPropertyAnimation(self.effect, b"opacity") self.effect.setOpacity(1) self.fade_anim.setDuration(150) self.fade_anim.setStartValue(0) self.fade_anim.setEndValue(1) self.fade_anim.setEasingCurve(QEasingCurve.InQuad) self.fade_anim.finished.connect(self.finish) def finish(self): self.done = True def moveEvent(self, event): super().moveEvent(event) if self.pos().y() < 110 + self.max * 50 and not self.done: self.fade_anim.start()
def __init__(self, name='', parent=None): QtWidgets.QDialog.__init__(self, parent) self.ui = uic.loadUi( os.path.join(os.path.dirname(__file__), "monitoring.ui")) self.mine_dialog = QtWidgets.QDialog(parent) uic.loadUi(os.path.join(os.path.dirname(__file__), "dialog.ui"), self.mine_dialog) opacity_effect = QGraphicsOpacityEffect(self.mine_dialog) opacity_effect.setOpacity(0) # self.ui.setWindowFlags(Qt.SplashScreen) # 윈도우 타이틀 없애기 self.ui.listWidget_4.setSpacing(30) if name != '': self.ui.label.setText(self.ui.label.text() + ': %s' % name) self.queue_thread = ReadThread() self.queue_thread.add_peer_sig.connect(self.add_node) self.queue_thread.log_sig.connect(self.handle_log) self.queue_thread.frame_sig.connect(self.change_status_text) self.queue_thread.bl_sig.connect(self.handle_block) self.queue_thread.tx_sig.connect(self.handle_tx) self.queue_thread.rm_peer_sig.connect(self.remove_node) self.queue_thread.full_sig.connect(self.open_mine_dialog) self.ui.pushButton.clicked.connect(self.send_sig_handler) self.send_handler = None self.mine_handler = None self.queue_thread.start() self.ui.show()
def INIT(self): self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) desktopRect = QDesktopWidget().screenGeometry() self.setGeometry(desktopRect) self.setStyleSheet('''background-color:black; ''') #self.setWindowOpacity(0.4) self.setCursor(Qt.CrossCursor) self.blackMask = QBitmap(desktopRect.size()) self.blackMask.fill(Qt.black) self.mask = self.blackMask.copy() self.isDrawing = False self.startPoint = QPoint() self.endPoint = QPoint() self.bg = QLabel(self) self.bg.lower() self.fg = QLabel(self) self.fg.raise_() self.fg.setPixmap(self.blackMask) op = QGraphicsOpacityEffect() op.setOpacity(0.4) self.fg.setGraphicsEffect(op) self.hotkeysignal.connect(self.syshotkeyaction) self.syskeysignal = SystemHotkey() self.syskeysignal.register(('control', 'shift', 'q'), callback=lambda x: self.hotkeysignal.emit(), overwrite=True)
def init_widget(self): self.setWindowTitle("Hello World") self.setGeometry(100, 100, 640, 480) # 창 위치, 크기 설정 self.setMouseTracking(True) # 마우스 움직임을 캐치 # QLabel 인스턴스 생성 # 인자값으로 parent인 self 지정 # QLabel(str, parent), QLabel(parent) 등으로 줄 수 있음 self.lb.setStyleSheet("background-color: yellow") # 라벨위젯과의 구분을 위한 색 self.lb.setMouseTracking( True) # False 값일 경우 Label 위젯에서는 mouse 이벤트가 발생하지 않는다. msg = self.get_properties_value( self.properties_list) # property 이름과 값을 돌려주는 함수 호출 self.lb.setText(msg) # Label에 텍스트 설정 # 맨 아래 놓이게 될 위젯 # 투명도를 설정하지 않음 self.w1.setGeometry(10, 10, 100, 100) self.w1.setStyleSheet("background-color: yellow") # 중간에 놓이게 될 위젯 # 투명도를 설정하지 않음 self.w3.setGeometry(40, 40, 100, 100) self.w3.setStyleSheet("background-color: pink") # 가장 위에 놓이게 될 위젯 self.w2.setGeometry(70, 70, 100, 100) opacity_effect = QGraphicsOpacityEffect(self.w2) opacity_effect.setOpacity(0.3) self.w2.setGraphicsEffect(opacity_effect) self.w2.setStyleSheet("background-color: red")
def setLabels(self, labels, opacity=0.5): """ the labels are provided as a 2-d numpyarray 0 is background """ rgb = label2rgb(labels, bg_label=0) # generate alpha alpha = np.ones(labels.shape) alpha[labels == 0] = 0 overlay = np.dstack((rgb, alpha)) pixmap = any2pixmap(overlay) effect = QGraphicsOpacityEffect() effect.setOpacity(opacity) item = QGraphicsPixmapItem() item.setPixmap(pixmap) item.setGraphicsEffect(effect) if self._handles['labels'] is not None: self.scene.removeItem(self._handles['labels']) self.scene.addItem(item) self._handles['labels'] = item
def memoDisplay(self, val): op = QGraphicsOpacityEffect() if val: op.setOpacity(0.9999) self.setGraphicsEffect(op) else: op.setOpacity(0) self.setGraphicsEffect(op)
def addCloseButton(self): self.button = QPushButton('x', self) buttonOpacity = QGraphicsOpacityEffect() buttonOpacity.setOpacity(0.45) self.button.setGraphicsEffect(buttonOpacity) self.button.move(0, 0) self.button.show() self.button.setVisible(False) self.button.clicked.connect(lambda: self.tabDeleted.emit(self))
def apply_text_rows(): c = qApp.allWidgets() for i in c: if i.metaObject().className() == 'IDADockWidget': i.setStyleSheet('background-color:transparent;') elif i.metaObject().className() == 'TextArrows': opacityEffect = QGraphicsOpacityEffect() i.setGraphicsEffect(opacityEffect) opacityEffect.setOpacity(0.3)
def pmt2_clicked(self): unuse = QGraphicsOpacityEffect() unuse.setOpacity(0.3) useable = QGraphicsOpacityEffect() useable.setOpacity(1) self.comboBox_4.setGraphicsEffect(unuse) self.label_9.setGraphicsEffect(unuse) self.comboBox_5.setGraphicsEffect(useable) self.label_10.setGraphicsEffect(useable)
class AngleButton(QPushButton): pressed = pyqtSignal(int) def __init__(self, value, parent=None): super().__init__(str(value), parent) self.setFont(QFont("Consolas", 16, 3)) self.setFixedSize(100, 50) self.index = value self.activated = False self.clicked.connect(lambda: self.pressed.emit(self.index)) self.activate(False) self.setup_fade() def moveEvent(self, event): super().moveEvent(event) if self.pos().y() < 55 and not self.faded: self.faded = True self.fade_anim.start() def activate(self, active): if active: self.setStyleSheet(""" AngleButton {background-color: lime} AngleButton:pressed { background-color: cyan } """) self.activated = True else: self.setStyleSheet(""" AngleButton {background-color: none} AngleButton:pressed { background-color: cyan } """) self.activated = False def disable(self, state): if state: self.setEnabled(False) else: self.setEnabled(True) self.activate(self.activated) self.setup_fade() def setup_fade(self): self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) self.effect.setOpacity(1) self.fade_anim = QPropertyAnimation(self.effect, b"opacity") self.fade_anim.setDuration(80) self.fade_anim.setStartValue(1) self.fade_anim.setEndValue(0) self.fade_anim.setEasingCurve(QEasingCurve.OutQuad) self.faded = False
def log_browser_filed_set(self): # log_browser_filed_name = QLabel(self) # log_browser_filed_name.setGeometry(20, 250, 160, 40) # log_browser_filed_name.setFont(QFont("Timers", 14)) # log_browser_filed_name.setText("弹幕日志") QApplication.processEvents() self.log_browser.setGeometry(1, 300, 1525, 500) self.log_browser.setStyleSheet("""background:#E98316""") # “#167ce9” op = QGraphicsOpacityEffect(self) op.setOpacity(0.5) self.log_browser.setGraphicsEffect(op)
class Indicator(QWidget): instance = None def __init__(self, parent=None): super().__init__(parent) self._effect = QGraphicsOpacityEffect(self) self.setGraphicsEffect(self._effect) self._effect.setOpacity(1.) box = QHBoxLayout(self) self._label = QLabel() font = self._label.font() font.setPixelSize(18) self._label.setFont(font) box.addWidget(self._label) palette = self.palette() palette.setColor(QPalette.Text, palette.color(QPalette.Window)) self._label.setPalette(palette) def run(self, ms): self.show() self.raise_() QTimer.singleShot(ms, self.show_indicator) def show_indicator(self): animation = QPropertyAnimation(self._effect, b"opacity", self) animation.setDuration(200) animation.setEndValue(0.) animation.start(QPropertyAnimation.DeleteWhenStopped) def set_text(self, text): self._label.setText(text) width = self.parent().width() x = width - (self._label.sizeHint().width() + 50) y = self.parent().rect().y() self.move(x, y + 10) def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(self.palette().color(QPalette.AlternateBase)) painter.setPen(Qt.NoPen) painter.drawRoundedRect(self.rect(), 1, 1) @classmethod def show_text(cls, parent, text, ms=1500): if cls.instance is not None: cls.instance.deleteLater() cls.instance = None cls.instance = Indicator(parent) cls.instance.set_text(text) cls.instance.run(ms)
def fadeInAnimator(obj): opacity_effect = QGraphicsOpacityEffect(self) opacity_effect.setOpacity(0) self.setGraphicsEffect(opacity_effect) self.fadeIn = QPropertyAnimation(opacity_effect, b"opacity") self.fadeIn.setDuration(350) self.fadeIn.setStartValue(0) self.fadeIn.setEndValue(1) self.fadeIn.setEasingCurve(QEasingCurve.InCubic) self.fadeIn.start(QPropertyAnimation.DeleteWhenStopped)
def login_toggle_password_visibility(self): """Toggles password visibility in the user login form""" if self.login_dock.visible_password: effect = QGraphicsOpacityEffect(self.login_dock.eye) effect.setOpacity(0.5) self.login_dock.eye.setGraphicsEffect(effect) self.login_dock.visible_password = False self.login_dock.password.setEchoMode(QLineEdit.Password) else: self.login_dock.eye.setGraphicsEffect(None) self.login_dock.visible_password = True self.login_dock.password.setEchoMode(QLineEdit.Normal)
def make_prompt_preset(self, opacity=DEFAULT_PROMPT_OPACITY): self.is_prompt = True op = QGraphicsOpacityEffect(self) op.setOpacity(opacity) self.setGraphicsEffect(op) self.setAutoFillBackground(False) self.setContextMenuPolicy(Qt.PreventContextMenu) self.set_inactive_icon() for f in self.fields: f.setText(". . . . . .")
class OpacityAniStackedWidget(QStackedWidget): """ 带淡入淡出动画效果的堆叠窗口类 """ def __init__(self, parent=None): super().__init__(parent) # 记录动画完成后需要切换到的窗口下标 self.__nextIndex = 0 # 给第二个窗口添加的淡入淡出动画 self.__opacityEffect = QGraphicsOpacityEffect(self) self.__opacityAni = QPropertyAnimation( self.__opacityEffect, b'opacity') # 初始化动画 self.__opacityEffect.setOpacity(0) self.__opacityAni.setDuration(220) self.__opacityAni.finished.connect(self.__aniFinishedSlot) def addWidget(self, widget): """ 向窗口中添加堆叠窗口 """ if self.count() == 2: raise Exception('最多只能有两个堆叠窗口') super().addWidget(widget) # 给第二个窗口设置淡入淡出效果 if self.count() == 2: self.widget(1).setGraphicsEffect(self.__opacityEffect) def setCurrentIndex(self, index: int): """ 切换当前堆叠窗口 """ # 如果当前下标等于目标下标就直接返回 if index == self.currentIndex(): return if index == 1: self.__opacityAni.setStartValue(0) self.__opacityAni.setEndValue(1) super().setCurrentIndex(1) elif index == 0: self.__opacityAni.setStartValue(1) self.__opacityAni.setEndValue(0) else: raise Exception('下标不能超过1') # 强行显示被隐藏的 widget(0) self.widget(0).show() self.__nextIndex = index self.__opacityAni.start() def setCurrentWidget(self, widget): """ 切换当前堆叠窗口 """ self.setCurrentIndex(self.indexOf(widget)) def __aniFinishedSlot(self): """ 动画完成后切换当前窗口 """ super().setCurrentIndex(self.__nextIndex)
def init_cursor(self, w, h): cursor = QWidget(self) cursor.setAttribute(Qt.WA_TransparentForMouseEvents) effect = QGraphicsOpacityEffect(cursor) effect.setOpacity(0.4) cursor.setGraphicsEffect(effect) cursor.setGeometry(0, 0, w, h) cursor.setAutoFillBackground(True) p = cursor.palette() p.setColor(cursor.backgroundRole(), QColor(self.conf['colors']['cursor'])) cursor.setPalette(p) cursor.hide() return cursor
def init_eraser(self, w, h): eraser = QWidget(self) eraser.setAttribute(Qt.WA_TransparentForMouseEvents) effect = QGraphicsOpacityEffect(eraser) effect.setOpacity(0.4) eraser.setGraphicsEffect(effect) eraser.setGeometry(0, 0, w, h) eraser.setAutoFillBackground(True) p = eraser.palette() p.setColor(eraser.backgroundRole(), QColor(self.conf['colors']['eraser'])) eraser.setPalette(p) eraser.hide() return eraser
def 初始化UI(self): icon = store.get("/app/window/icon") bgImg = store.get("/app/window/background_image") self.setStyleSheet('''QToolTip { background-color: black; color: white; border: 0px }''') self.setFixedSize(960, 560) self.setWindowTitle("登记设置") self.setWindowIcon(icon) backgroundColorLabel = QLabel(self) backgroundColorLabel.resize(self.width(), self.height()) backgroundColorLabel.setStyleSheet( "QLabel{background-color:rgba(50,50,50,1)}") graphicsEffect = QGraphicsOpacityEffect() graphicsEffect.setOpacity(0.1) backgroundImageLabel = QLabel(self) backgroundImageLabel.setPixmap(bgImg) backgroundImageLabel.move(0, int((self.height() - 1230) / 6)) backgroundImageLabel.setGraphicsEffect(graphicsEffect) borderLabel = QLabel(self) borderLabel.resize(self.width() - 4, self.height() - 2) borderLabel.move(2, -1) borderLabel.setStyleSheet("QLabel{border:1px solid black}") yesButton = QPushButton("应用", self) yesButton.move(700, 500) yesButton.resize(80, 24) yesButton.setStyleSheet(按钮样式) yesButton.clicked.connect(lambda _: self.设置换装()) cancelButton = QPushButton("取消", self) cancelButton.move(790, 500) cancelButton.resize(80, 24) cancelButton.setStyleSheet(按钮样式) cancelButton.clicked.connect(lambda _: self.closeWindow()) resetButton = QPushButton("全部重置", self) resetButton.move(700, 460) resetButton.resize(170, 24) resetButton.setStyleSheet(按钮样式) resetButton.clicked.connect(lambda _: self.reset()) self.初始化自选装备UI() self.初始化奥兹玛UI() self.初始化希洛克UI() self.初始化遴选UI() self.初始化残香UI()
def initialize_animation(obj): # Create an opacity animation that can be started later: # Set up the fade in animation now, initiate later: opacity = QGraphicsOpacityEffect() opacity.setOpacity(0) obj.setGraphicsEffect(opacity) obj.opacity_animation = QPropertyAnimation(obj.graphicsEffect(), "opacity".encode()) obj.opacity_animation.setDuration(200) obj.opacity_animation.setStartValue(0) obj.opacity_animation.setEndValue(1) obj.delay = QTimer() obj.delay.setSingleShot(True) obj.delay.timeout.connect(obj.opacity_animation.start)
def set_accessable(self, value): """ Переключатель для изменения состояния возможности взаимодействовать с виджетом """ for card in self.get_cards(): card.widget().setEnabled(value) p = self.palette() p.setColor(self.backgroundRole(), Qt.transparent) op = QGraphicsOpacityEffect(self) if value: op.setOpacity(1.0) else: op.setOpacity(0.4) self.setGraphicsEffect(op) #self.setAutoFillBackground(False) self.setPalette(p)
def __init__(self, parent=None, f=Qt.ToolTip | Qt.FramelessWindowHint): super(Notification, self).__init__(parent, f) self.parent = parent self.theme = self.parent.theme self.setObjectName('notification') self.setWindowModality(Qt.NonModal) self.setMinimumWidth(450) self._title, self._message = '', '' self._icons = dict() self.buttons = list() self.msgLabel = QLabel(self) self.msgLabel.setWordWrap(True) logo = QPixmap(82, 82) logo.load(':/images/vidcutter-small.png', 'PNG') logo_label = QLabel(self) logo_label.setPixmap(logo) self.left_layout = QVBoxLayout() self.left_layout.addWidget(logo_label) self.right_layout = QVBoxLayout() self.right_layout.addWidget(self.msgLabel) if sys.platform != 'win32': effect = QGraphicsOpacityEffect() effect.setOpacity(1) self.window().setGraphicsEffect(effect) self.animations = QSequentialAnimationGroup(self) self.pauseAnimation = self.animations.addPause( int(self.duration / 2 * 1000)) opacityAnimation = QPropertyAnimation(effect, b'opacity', self.animations) opacityAnimation.setDuration(2000) opacityAnimation.setStartValue(1.0) opacityAnimation.setEndValue(0.0) opacityAnimation.setEasingCurve(QEasingCurve.InOutQuad) self.animations.addAnimation(opacityAnimation) self.animations.finished.connect(self.close) self.shown.connect(self.fadeOut) else: self.shown.connect( lambda: QTimer.singleShot(self.duration * 1000, self.fadeOut)) layout = QHBoxLayout() layout.addStretch(1) layout.addLayout(self.left_layout) layout.addSpacing(10) layout.addLayout(self.right_layout) layout.addStretch(1) self.setLayout(layout)
def add_session(self,item): # 新建桌面按钮 pb_session = QPushButton(item["name"]) pb_session.setSizePolicy(self.session_bt_size_policy) pb_session.setMaximumSize(self.session_btn_size) # 设置桌面按钮为半透明 op = QGraphicsOpacityEffect() op.setOpacity(0.9) pb_session.setGraphicsEffect(op) pb_session.setAutoFillBackground(True) # TODO 待删除 # pb_session.session_id = item["id"] # pb_session.picture = item["picture"] pb_session.item = item pb_session.clicked.connect(self.on_pb_session_clicked) self.hl_session.addWidget(pb_session) return pb_session
def fade_to_left_ani(self, widget: QWidget): widget_move_ani = QPropertyAnimation(widget, b'pos', self) widget_move_ani.setStartValue(QPoint(244, widget.y())) widget_move_ani.setEndValue(QPoint(50, widget.y())) widget_move_ani.setDuration(200) widget_move_ani.setEasingCurve(QEasingCurve.InCurve) opacity = QGraphicsOpacityEffect(self) opacity.setOpacity(1.0) widget.setGraphicsEffect(opacity) widget_fade_ani = QPropertyAnimation(opacity, b'opacity', self) widget_fade_ani.setStartValue(1.0) widget_fade_ani.setEndValue(0.0) widget_fade_ani.setDuration(200) widget_fade_ani.setEasingCurve(QEasingCurve.InCurve) return widget_move_ani, widget_fade_ani
class Window(QMainWindow, Ui_MainWindow): def __init__(self): super(Window, self).__init__() self.setupUi(self) fname = QFileDialog.getOpenFileName(self, 'Выбрать картинку', '')[0] self.opacity_effect = QGraphicsOpacityEffect() self.opacity_effect.setOpacity(1) self.pixmap = QPixmap(fname) self.label.setPixmap(self.pixmap) self.label.setGraphicsEffect(self.opacity_effect) self.verticalSlider.valueChanged.connect(self.change_alpha) self.show() def change_alpha(self, value): print(value) print(1 - (value / 100)) self.opacity_effect.setOpacity(1 - (value / 100))
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 SliderArea(QFrame): def __init__(self, parent): super(SliderArea, self).__init__(parent) self._parent = parent self.setMouseTracking(True) self.setCursor(Qt.OpenHandCursor) color = resources.CUSTOM_SCHEME.get('current-line', resources.COLOR_SCHEME['current-line']) print("color", color, resources.COLOR_SCHEME['current-line']) if ACTIVATE_OPACITY: self.setStyleSheet("background: %s;" % color) self.goe = QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(settings.MINIMAP_MAX_OPACITY / 2) else: self.setStyleSheet("background: transparent;") self.pressed = False self.__scroll_margins = None def paintEvent(self, event): """Paint over the widget to overlay its content.""" if not ACTIVATE_OPACITY: color = QColor(255, 255, 255, 80) brush = QBrush(color) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.Antialiasing, True) painter.fillRect(event.rect(), brush) painter.setPen(QPen(Qt.NoPen)) painter.end() super(SliderArea, self).paintEvent(event) def update_position(self): font_size = QFontMetrics(self._parent.font()).height() height = self._parent.lines_count * font_size self.setFixedHeight(height) self.setFixedWidth(self._parent.width()) self.__scroll_margins = (height, self._parent.height() - height) def move_slider(self, y): self.move(0, y) def mousePressEvent(self, event): super(SliderArea, self).mousePressEvent(event) self.pressed = True self.setCursor(Qt.ClosedHandCursor) def mouseReleaseEvent(self, event): super(SliderArea, self).mouseReleaseEvent(event) self.pressed = False self.setCursor(Qt.OpenHandCursor) def mouseMoveEvent(self, event): super(SliderArea, self).mouseMoveEvent(event) if self.pressed: pos = self.mapToParent(event.pos()) y = pos.y() - (self.height() / 2) if y < 0: y = 0 if y < self.__scroll_margins[0]: self._parent.verticalScrollBar().setSliderPosition( self._parent.verticalScrollBar().sliderPosition() - 2) elif y > self.__scroll_margins[1]: self._parent.verticalScrollBar().setSliderPosition( self._parent.verticalScrollBar().sliderPosition() + 2) self.move(0, y) self._parent.scroll_area(pos, event.pos())
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 MiniMap(QsciScintilla): def __init__(self, parent): super(MiniMap, self).__init__(parent) #self.setWordWrapMode(QTextOption.NoWrap) #self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) #self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.SendScintilla(QsciScintilla.SCI_SETBUFFEREDDRAW, 0) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0) self.setMarginWidth(1, 0) self.setFolding(self.NoFoldStyle, 2) #self.setCenterOnScroll(True) self.setMouseTracking(True) #self.viewport().setCursor(Qt.PointingHandCursor) #self.setTextInteractionFlags(Qt.NoTextInteraction) self.Document = parent #self.highlighter = None # self.lines_count = 0 self.Locked = False # self.Document.updateRequest['const QRect&', int].connect(self.update_visible_area) self.connect_DocumentSignal() 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.changeSliderHeight() # self.viewport().resizeEvent['QResizeEvent*'].connect(\ # lambda e: QTimer.singleShot(200, self.changeSliderHeight)) # self.slider.show() self.setReadOnly(True) def changeSliderHeight(self): self.slider.setFixedHeight(self.viewport().geometry().height()) def connect_DocumentSignal(self): self.Document.SCN_UPDATEUI[int].connect(self.update_visible_area) def disconnect_DocumentSignal(self): self.Document.SCN_UPDATEUI[int].disconnect(self.update_visible_area) def Lock_DocumentSignal(self): self.Locked = True def unLock_DocumentSignal(self): self.Locked = False # def disconnect_MinimapSignal(self): # self.SCN_UPDATEUI[int].disconnect(self.update_visible_area) # def connect_MinimapSignal(self): # self.SCN_UPDATEUI[int].connect(self.update_visible_area) # def shutdown(self): # self.Document.updateRequest['const QRect&', int].disconnect(self.update_visible_area) def __calculate_max(self): #line_height = self.Document.cursorRect().height() #if line_height > 0: #self.lines_count = self.Document.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.Document.height()) self.setFixedWidth(self.Document.width() * settings.SIZE_PROPORTION) x = self.Document.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 self.Locked: return #if not self.slider.pressed: # line_number = self.Document.firstVisibleBlock().blockNumber() # block = self.document().findBlockByLineNumber(line_number) #print("\nself.Document.getCursorPosition():", self.Document.getCursorPosition(), self.Document.firstVisibleLine()) # cursor = self.textCursor() # self.setFirstVisibleLine(self.Document.firstVisibleLine()) l1 = self.Document.firstVisibleLine() # l2 = self.firstVisibleLine() # p1 = self.Document.getCursorPosition() # p2 = self.getCursorPosition() # self.setCursorPosition(*self.Document.getCursorPosition())#block.position()) # rect = self.cursorRect(cursor) # self.setTextCursor(cursor) # self.slider.move_slider((l1-l2)*QFontMetrics(self.Document.font()).height()/3.2)# arbitraty value! # self.slider.move_slider(l1*QFontMetrics(self.Document.font()).height()/3.2)# arbitraty value! self.slider.move_slider(l1*QFontMetrics(self.font()).lineSpacing()/3.2) #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.Document.jump_to_line(cursor.blockNumber()) def move_Document(self, y): self.Document.move_Document(y) # self.Document.fillIndicatorRange(4,0, 12,0, 1) def resizeEvent(self, event): super(MiniMap, self).resizeEvent(event) self.slider.update_position() # def scroll_area(self, posDocument, pos_slider):#ensureLineVisible # # posDocument.setY(posDocument.y() - pos_slider.y()) # line = self.lineAt(posDocument) # #self.Document.verticalScrollBar().setValue(line)# * QFontMetrics(self.font()).height()) # self.setFirstVisibleLine(line) def scroll_area(self, __Y):#ensureLineVisible # posDocument.setY(posDocument.y() - pos_slider.y()) line = self.lineAt(QPoint(1, __Y)) if line < 0: print("\n----LINE", line) line = self.lineAt(QPoint(1, __Y+1)) if line < 0: print("\n++++LINE", line) line = self.lineAt(QPoint(0, __Y)) if line < 0: print("\n*****LINE", line) line = self.lineAt(QPoint(0, __Y+1)) if line < 0: print("\n/////LINE", line) line = self.lineAt(QPoint(1, __Y-1)) #self.Document.verticalScrollBar().setValue(line)# * QFontMetrics(self.font()).height()) self.Lock_DocumentSignal() self.Document.setFirstVisibleLine(line) print("\nLINE", line, __Y) self.unLock_DocumentSignal() def scroll_area2(self, pos):#ensureLineVisible # posDocument.setY(posDocument.y() - pos_slider.y()) line = self.lineAt(pos) #self.Document.verticalScrollBar().setValue(line)# * QFontMetrics(self.font()).height()) self.Lock_DocumentSignal() # self.Document.setFirstVisibleLine(pos.y()/QFontMetrics(self.font()).lineSpacing()*3.4) bar = self.Document.verticalScrollBar() lenght = bar.maximum() - bar.minimum() bar.setSliderPosition(pos.y()) self.unLock_DocumentSignal() def wheelEvent(self, event): super(MiniMap, self).wheelEvent(event) self.Document.wheelEvent(event) def inputMethodEvent(self, event): print("inputMethodEvent::", event.attributes())#Selection super(MiniMap, self).inputMethodEvent(event)
class SliderArea(QFrame): def __init__(self, parent): super(SliderArea, self).__init__(parent) self.minimap = parent self.setMouseTracking(True) self.setCursor(Qt.OpenHandCursor) color = resources.CUSTOM_SCHEME.get( 'CurrentLine', resources.COLOR_SCHEME['CurrentLine']) if ACTIVATE_OPACITY: print("\nACTIVATE_OPACITY") # self.setStyleSheet("background: %s;" % color) self.setStyleSheet("background-color: rgb(203, 186, 98);")#↔167, 167, 167, 100);") self.goe = QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(settings.MINIMAP_MAX_OPACITY / 2) else: self.setStyleSheet("background: transparent;") self.pressed = False self.__scroll_margins = None def paintEvent(self, event): """Paint over the widget to overlay its content.""" if not ACTIVATE_OPACITY: painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.Antialiasing, True) painter.fillRect(event.rect(), QBrush( QColor(255, 255, 255, 80))) painter.setPen(QPen(Qt.NoPen)) painter.end() super(SliderArea, self).paintEvent(event) def update_position(self): font_size = QFontMetrics(self.minimap.font()).lineSpacing() # height = self.minimap.lines() / 5.1 * font_size _view = self.minimap.Document.viewport() # height = _view.height() / self.minimap.Document.height() * self.minimap.height()# font_size / height = _view.height() * settings.SIZE_PROPORTION * 1.22#1.2# font_size / print("\nHeight:", height) self.setFixedHeight(height) self.setFixedWidth(self.minimap.width()) self.__scroll_margins = (height, self.minimap.height() - height) def move_slider(self, y): self.move(0, y) def move__slider(self, y): geo = self.geometry() geo.setY(y) self.setGeometry(geo) def mousePressEvent(self, event): super(SliderArea, self).mousePressEvent(event) self.pressed = True self.setCursor(Qt.ClosedHandCursor) def mouseReleaseEvent(self, event): super(SliderArea, self).mouseReleaseEvent(event) self.pressed = False self.setCursor(Qt.OpenHandCursor) def mouseMoveEvent(self, event): super(SliderArea, self).mouseMoveEvent(event) if self.pressed: pos = self.mapToParent(event.pos()) y = pos.y() - (self.height() / 2) if y < 0: y = 0 # if y < self.__scroll_margins[0]: # self.minimap.verticalScrollBar().setSliderPosition( # self.minimap.verticalScrollBar().sliderPosition() - 2) # elif y > self.__scroll_margins[1]: # self.minimap.verticalScrollBar().setSliderPosition( # self.minimap.verticalScrollBar().sliderPosition() + 2) self.move_slider(y) # self.minimap.scroll_area(pos, event.pos()) _pos = pos # _pos.setY(y) # _pos.setY(-pos.y() + self.mapToParent(self.pos()).y()) # self.minimap.scroll_area(self.mapToParent(self.pos()).y()) self.minimap.scroll_area2(self.pos()) # _event = QMouseEvent(QEvent.MouseMove, pos, event.windowPos(),\ # event.screenPos(), event.button(), \ # event.buttons(), event.modifiers()) # self.minimap.mouseMoveEvent(_event) # self.minimap.move_Document(y) def function(self): l1 = self.minimap.firstVisibleLine() l2 = self.firstVisibleLine() p1 = self.minimap.getCursorPosition() p2 = self.getCursorPosition() # self.setCursorPosition(*self.minimap.getCursorPosition())#block.position()) # rect = self.cursorRect(cursor) # self.setTextCursor(cursor) self.slider.move_slider((l1-l2)*QFontMetrics(self.minimap.font()).height()/4)#(p1[0]-p2[0]) def wheelEvent(self, event): super(SliderArea, self).wheelEvent(event) self.minimap.wheelEvent(event)