以下是一个使用 Python 和 PySide6 创建的程序,满足您描述的功能。这个程序创建了一个始终在最前端的窗口,包含两个垂直排列的悬浮按钮。上方按钮在按住时会持续向上滚动当前活动窗口,下方按钮在按住时会持续向下滚动当前活动窗口。窗口可以自由拖拽移动。
python
import sys
import threading
import time
from PySide6.QtCore import Qt, QPoint
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from pynput.mouse import Controller as MouseController
class ScrollButton(QPushButton):
def __init__(self, label, direction, parent=None):
super().__init__(label, parent)
self.direction = direction # 'up' 或 'down'
self.is_pressed = False
self.scroll_thread = None
self.mouse = MouseController()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.is_pressed = True
self.scroll_thread = threading.Thread(target=self.scroll_continuously, daemon=True)
self.scroll_thread.start()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.is_pressed = False
def scroll_continuously(self):
while self.is_pressed:
if self.direction == 'up':
self.mouse.scroll(0, 1) # 向上滚动
elif self.direction == 'down':
self.mouse.scroll(0, -1) # 向下滚动
time.sleep(0.05) # 调整滚动速度(秒)
class DraggableWindow(QWidget):
def __init__(self):
super().__init__()
# 设置窗口始终在最前端且无边框
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.init_ui()
self.dragging = False
self.drag_position = QPoint()
def init_ui(self):
layout = QVBoxLayout()
layout.setSpacing(5)
layout.setContentsMargins(5, 5, 5, 5)
# 创建上滚和下滚按钮
self.up_button = ScrollButton("上滚", 'up', self)
self.down_button = ScrollButton("下滚", 'down', self)
# 设置按钮样式(可根据需要调整)
button_style = """
QPushButton {
background-color: #3498db;
color: white;
border: none;
border-radius: 5px;
height: 40px;
font-size: 14px;
}
QPushButton:pressed {
background-color: #2980b9;
}
"""
self.up_button.setStyleSheet(button_style)
self.down_button.setStyleSheet(button_style)
layout.addWidget(self.up_button)
layout.addWidget(self.down_button)
self.setLayout(layout)
self.setFixedSize(100, 100) # 根据需要调整窗口大小
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragging = True
self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton and self.dragging:
self.move(event.globalPosition().toPoint() - self.drag_position)
event.accept()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragging = False
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = DraggableWindow()
window.show()
sys.exit(app.exec())