Sure! Below is the modified version of your Python script. It includes two additional mini buttons labeled “+” and “-” to adjust the transparency (opacity) of the floating window. The opacity can be increased or decreased within a defined range to ensure the window remains visible and usable.
Changes Overview:
- Added Opacity Buttons: Two new buttons (“+” and “-”) are added to adjust the window's opacity.
- Layout Adjustments: Organized the buttons using
QHBoxLayout to place the opacity buttons horizontally below the scroll buttons.
- Opacity Management: Implemented methods to increase and decrease the window's opacity, ensuring it stays within the range of 0.2 to 1.0.
- Button Styling: Styled the opacity buttons to differentiate them from the scroll buttons.
Complete Modified Code:
import sys
import ctypes
import platform
from PySide6.QtCore import Qt, QPoint, QTimer
from PySide6.QtWidgets import (
QApplication,
QWidget,
QPushButton,
QVBoxLayout,
QHBoxLayout,
)
from pynput.mouse import Controller as MouseController
# Windows-specific constants and functions
if platform.system() == "Windows":
GWL_EXSTYLE = -20
WS_EX_NOACTIVATE = 0x08000000
WS_EX_TOOLWINDOW = 0x00000080
def set_window_noactivate(widget):
hwnd = widget.winId().__int__()
ex_style = ctypes.windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
ex_style |= WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW
ctypes.windll.user32.SetWindowLongW(hwnd, GWL_EXSTYLE, ex_style)
class ScrollButton(QPushButton):
def __init__(self, label, direction, parent=None):
super().__init__(label, parent)
self.direction = direction # 'up' or 'down'
self.mouse = MouseController()
# Set the button to not accept focus
self.setFocusPolicy(Qt.NoFocus)
# Use QTimer to implement continuous scrolling
self.timer = QTimer()
self.timer.timeout.connect(self.scroll_step)
def scroll_step(self):
if self.direction == 'up':
self.mouse.scroll(0, 1) # Scroll up
elif self.direction == 'down':
self.mouse.scroll(0, -1) # Scroll down
def mousePressEvent(self, event):
if event.button() == Qt.RightButton: # Changed to right-click
self.timer.start(50) # Scroll every 50 ms; adjust for speed
super().mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.RightButton: # Changed to right-click
self.timer.stop()
super().mouseReleaseEvent(event)
class DraggableWindow(QWidget):
def __init__(self):
super().__init__()
# Set window flags to stay on top, frameless, and not activate on show
self.setWindowFlags(
Qt.WindowStaysOnTopHint |
Qt.FramelessWindowHint |
Qt.Tool
)
self.setAttribute(Qt.WA_ShowWithoutActivating) # Show without activating
self.setAttribute(Qt.WA_TranslucentBackground, True) # Optional: transparent background
self.setFocusPolicy(Qt.NoFocus)
self.opacity_level = 0.8 # Initial opacity
self.setWindowOpacity(self.opacity_level)
self.init_ui()
self.dragging = False
self.drag_position = QPoint()
# Platform-specific settings
if platform.system() == "Windows":
set_window_noactivate(self)
elif platform.system() == "Linux":
# Additional settings for Linux if needed
pass
elif platform.system() == "Darwin":
# Additional settings for macOS if needed
pass
def init_ui(self):
main_layout = QVBoxLayout()
main_layout.setSpacing(10)
main_layout.setContentsMargins(10, 10, 10, 10)
# Create up and down scroll buttons
self.up_button = ScrollButton("⬆️ 上滚", 'up', self)
self.down_button = ScrollButton("⬇️ 下滚", 'down', self)
# Set scroll button styles
scroll_button_style = """
QPushButton {
background-color: rgba(52, 152, 219, 0.8);
color: white;
border: none;
border-radius: 5px;
height: 40px;
font-size: 14px;
}
QPushButton:pressed {
background-color: rgba(41, 128, 185, 0.8);
}
QPushButton:hover {
background-color: rgba(52, 152, 219, 1);
}
"""
self.up_button.setStyleSheet(scroll_button_style)
self.down_button.setStyleSheet(scroll_button_style)
main_layout.addWidget(self.up_button)
main_layout.addWidget(self.down_button)
# Create a horizontal layout for opacity buttons
opacity_layout = QHBoxLayout()
opacity_layout.setSpacing(5)
opacity_layout.setContentsMargins(0, 0, 0, 0)
# Create opacity decrease button
self.opacity_down = QPushButton("-")
self.opacity_down.setFixedSize(30, 30)
self.opacity_down.setToolTip("降低透明度")
self.opacity_down.setStyleSheet(self.get_opacity_button_style())
# Create opacity increase button
self.opacity_up = QPushButton("+")
self.opacity_up.setFixedSize(30, 30)
self.opacity_up.setToolTip("增加透明度")
self.opacity_up.setStyleSheet(self.get_opacity_button_style())
# Connect opacity buttons to their functions
self.opacity_down.clicked.connect(self.decrease_opacity)
self.opacity_up.clicked.connect(self.increase_opacity)
# Add opacity buttons to the horizontal layout
opacity_layout.addWidget(self.opacity_down)
opacity_layout.addWidget(self.opacity_up)
# Add opacity layout to the main vertical layout
main_layout.addLayout(opacity_layout)
self.setLayout(main_layout)
self.setFixedSize(120, 150) # Adjusted window size to accommodate new buttons
def get_opacity_button_style(self):
# Style for the opacity buttons
return """
QPushButton {
background-color: rgba(231, 76, 60, 0.8);
color: white;
border: none;
border-radius: 3px;
font-size: 16px;
}
QPushButton:pressed {
background-color: rgba(192, 57, 43, 0.8);
}
QPushButton:hover {
background-color: rgba(231, 76, 60, 1);
}
"""
def increase_opacity(self):
if self.opacity_level < 1.0:
self.opacity_level += 0.1
if self.opacity_level > 1.0:
self.opacity_level = 1.0
self.setWindowOpacity(self.opacity_level)
def decrease_opacity(self):
if self.opacity_level > 0.2:
self.opacity_level -= 0.1
if self.opacity_level < 0.2:
self.opacity_level = 0.2
self.setWindowOpacity(self.opacity_level)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragging = True
# Get the mouse click position relative to the window
if hasattr(event, 'globalPosition'):
self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
else:
self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton and self.dragging:
# Calculate the new window position
if hasattr(event, 'globalPosition'):
new_pos = event.globalPosition().toPoint() - self.drag_position
else:
new_pos = event.globalPos() - self.drag_position
self.move(new_pos)
event.accept()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragging = False
event.accept()
# Override the event method to ensure the window does not get activated
def event(self, e):
if platform.system() == "Windows" and e.type() == 10: # QEvent.WindowActivate = 10
return False
return super().event(e)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = DraggableWindow()
window.show()
sys.exit(app.exec())
Detailed Explanation of the Additions:
-
Opacity Buttons Creation:
- Two
QPushButton instances, self.opacity_down ("-") and self.opacity_up ("+"), are created to decrease and increase the window's opacity, respectively.
- These buttons are styled with a distinct appearance to differentiate them from the scroll buttons.
-
Layout Integration:
- A
QHBoxLayout named opacity_layout is created to arrange the opacity buttons horizontally.
- This layout is added to the main vertical layout
main_layout below the existing scroll buttons.
- The window size is adjusted (
self.setFixedSize(120, 150)) to accommodate the additional buttons comfortably.
-
Opacity Adjustment Methods:
increase_opacity: Increases the window's opacity by 0.1, ensuring it does not exceed 1.0.
decrease_opacity: Decreases the window's opacity by 0.1, ensuring it does not go below 0.2 to maintain usability.
- Both methods update
self.opacity_level and apply the new opacity using self.setWindowOpacity(self.opacity_level).
-
Button Signal Connections:
-
Styling:
- The opacity buttons have a different color scheme (e.g., red hues) to make them easily identifiable.
- The scroll buttons retain their original blue color scheme.
-
Tooltips:
Running the Script:
To run the modified script, ensure you have the required libraries installed:
pip install PySide6 pynput
Then, save the script to a file (e.g., floating_scroll.py) and execute it using Python:
python floating_scroll.py
A floating window with up/down scroll buttons and "+" / "-" opacity adjustment buttons will appear. You can drag the window using the left mouse button and adjust its transparency using the opacity buttons with right-click on the scroll buttons.
Additional Considerations:
- Opacity Increment Steps: The current implementation adjusts the opacity in steps of 0.1. You can modify this value for finer or coarser control.
- Minimum Opacity: Set to 0.2 to prevent the window from becoming too transparent. Adjust as needed.
- Platform Compatibility: The opacity functionality works across different platforms, but ensure that your window manager or OS settings allow for window transparency.
- Customization: Feel free to customize the styles, button sizes, and layout to better fit your application's design requirements.
I hope this helps! Let me know if you need further assistance or additional features.