PySide2进度条
作者:YXN-python 阅读量:12 发布日期:2024-11-05
import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QSlider, QVBoxLayout, QWidget, QLabel
from PySide2.QtCore import Qt, QTimer, Signal
class ProgressBar(QSlider):
progress_changed = Signal(float) # 信号,播放进度改变时触发
def __init__(self, duration=100.0, parent=None):
super().__init__(Qt.Horizontal, parent)
self.setValue(0)
self.setFixedHeight(20)
self.setFixedWidth(400)
self.duration = duration
self.current_position = 0.0
self.is_slider_pressed = False
self.timer = QTimer()
self.timer.timeout.connect(self.update_progress)
logo_color = "#3498db"
self.setStyleSheet("""
QSlider::handle {
background-color: white;
border-radius: 5px;
width: 10px;
margin-top: -5px;
margin-bottom: -5px;
}
QSlider::groove {
border: 1px solid #666;
border-radius: 3px;
background-color: %s;
height: 6px;
}
QSlider::add-page {
background-color: #ddd;
border-radius: 3px;
}
""" % logo_color)
self.sliderPressed.connect(self.on_slider_pressed)
self.sliderReleased.connect(self.on_slider_released)
def update_progress(self):
if not self.is_slider_pressed and self.current_position < self.duration:
self.current_position += 0.1
value = (self.current_position / self.duration) * 100
self.setValue(value)
self.progress_changed.emit(self.current_position)
elif self.current_position >= self.duration:
self.timer.stop()
def on_slider_pressed(self):
self.is_slider_pressed = True
def on_slider_released(self):
self.is_slider_pressed = False
value = self.value()
self.current_position = (value / 100) * self.duration
self.progress_changed.emit(self.current_position)
print(f"当前播放位置: {self.current_position:.2f} / {self.duration}")
def start(self):
self.timer.start(100)
class MusicPlayer(QMainWindow):
def __init__(self):
super().__init__()
self.progress_bar = ProgressBar(duration=200.0)
self.progress_bar.progress_changed.connect(self.update_label)
self.label = QLabel("当前进度: 0.00 / 200.00")
layout = QVBoxLayout()
layout.addWidget(self.progress_bar)
layout.addWidget(self.label)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def update_label(self, position):
self.label.setText(f"当前进度: {position:.2f} / {self.progress_bar.duration}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MusicPlayer()
window.show()
window.progress_bar.start()
sys.exit(app.exec_())
YXN-python
2024-11-05