参考链接
PyQt5实现仿QQ贴边隐藏功能_一名新生程序员的日常-CSDN博客_pyqt5贴边隐藏
代码示例
import sys
from PyQt6.QtWidgets import QWidget, QPushButton, QApplication
from PyQt6.QtCore import Qt, QRect, QPoint, QPropertyAnimation
SCREEN_WEIGHT = 1920
SCREEN_HEIGHT = 1080
WINDOW_WEIGHT = 300
WINDOW_HEIGHT = 600
class AutoHide(QWidget):
def __init__(self):
super(AutoHide, self).__init__()
self.exit = QPushButton(self)
self.dragPosition = self.pos()
self.setup_ui()
self.resize(WINDOW_WEIGHT, WINDOW_HEIGHT)
self.show()
def setup_ui(self):
self.setWindowFlags(Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint
| Qt.WindowType.Tool) # 去掉标题栏
self.exit.setText(" 退出 ")
self.exit.move(QPoint(120, 400))
self.exit.clicked.connect(lambda: exit(0))
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.dragPosition = event.globalPosition().toPoint() - self.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.MouseButton.LeftButton:
self.move(event.globalPosition().toPoint() - self.dragPosition)
def enterEvent(self, event):
if self.pos().x() + WINDOW_WEIGHT >= SCREEN_WEIGHT: # 右侧显示
self.move_window(SCREEN_WEIGHT - WINDOW_WEIGHT + 2, self.pos().y())
event.accept()
elif self.pos().x() <= 0: # 左侧显示
self.move_window(0, self.pos().y())
event.accept()
def leaveEvent(self, event):
if self.pos().x() + WINDOW_WEIGHT >= SCREEN_WEIGHT: # 右侧隐藏
self.move_window(SCREEN_WEIGHT - 2, self.pos().y())
event.accept()
elif self.pos().x() <= 2: # 左侧隐藏
self.move_window(2 - WINDOW_WEIGHT, self.pos().y())
event.accept()
def move_window(self, width, height):
animation = QPropertyAnimation(self, b"geometry", self)
animation.setDuration(80)
new_pos = QRect(width, height, self.width(), self.height())
animation.setEndValue(new_pos)
animation.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
ui = AutoHide()
sys.exit(app.exec())