返回
Qt 小 Tip 集合:托盘最小化、升级小闹钟、计算文件 MD5 值等
后端
2023-12-03 22:51:58
在 PyQt5 中,可以轻松实现将应用程序最小化到托盘。这对于那些需要在后台运行的应用程序非常有用,比如媒体播放器、下载器等。
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon("icon.png"))
self.tray_icon.setToolTip("This is my application.")
self.menu = QMenu(self)
self.action_show = QAction("Show", self)
self.action_quit = QAction("Quit", self)
self.menu.addAction(self.action_show)
self.menu.addAction(self.action_quit)
self.tray_icon.setContextMenu(self.menu)
self.tray_icon.activated.connect(self.on_tray_icon_activated)
self.action_show.triggered.connect(self.show)
self.action_quit.triggered.connect(QApplication.quit)
self.tray_icon.show()
def on_tray_icon_activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.hide()
sys.exit(app.exec_())
通过修改系统注册表,可以升级小闹钟。具体来说,可以将闹钟声音文件替换为自己喜欢的音乐。
import winreg
def upgrade_alarm_clock():
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Alarm")
value, _ = winreg.QueryValueEx(key, "Default")
winreg.SetValueEx(key, "Default", 0, winreg.REG_SZ, r"C:\path\to\your\music.mp3")
winreg.CloseKey(key)
print("Alarm clock upgraded successfully.")
except Exception as e:
print(f"Failed to upgrade alarm clock: {e}")
if __name__ == "__main__":
upgrade_alarm_clock()
计算文件的 MD5 值可以用于文件校验、数据传输等场景。
import hashlib
def calculate_md5(file_path):
with open(file_path, "rb") as f:
data = f.read()
md5 = hashlib.md5(data).hexdigest()
return md5
if __name__ == "__main__":
file_path = "path/to/file.txt"
md5 = calculate_md5(file_path)
print(f"MD5 value of {file_path}: {md5}")
使用 PyQt5 创建一个定时任务非常简单。
import sys
from PyQt5.QtCore import QTimer, QDateTime
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel("Current Time: ")
self.button = QPushButton("Start Timer")
self.timer = QTimer()
self.timer.setInterval(1000)
self.timer.timeout.connect(self.update_time)
self.button.clicked.connect(self.start_timer)
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.layout.addWidget(self.button)
self.widget = QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
def start_timer(self):
self.timer.start()
def update_time(self):
current_time = QDateTime.currentDateTime()
self.label.setText(f"Current Time: {current_time.toString()}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
这些技巧只是 PyQt5 的冰山一角。PyQt5 还有很多其他有用的功能,等待你去探索。