PyQt4 初试牛刀二

时间:2021-09-23 04:01:23

一、最小话托盘后,调用showNormal()后窗口不刷新,解决办法如下:

    重写showNormal 方法,调用父类方法后,repaint窗体

def showNormal(self):
    super(LcdTime, self).showNormal()
    self.repaint()

二、透明显示窗口后无法拖动窗体:

    必须拖动非透明区域,比如数字,目前没有找到好的解决方案。

    PyQt4 初试牛刀二

# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui


class LcdTime(QtGui.QDialog):
    def __init__(self, parent=None):
        super(LcdTime, self).__init__(parent)

        self.hour = QtGui.QLCDNumber(8, self)
        self.hour.setGeometry(10, 10, 200, 80)
        self.hour.setSegmentStyle(QtGui.QLCDNumber.Flat)
        self.display()

        self.timer = QtCore.QTimer()
        self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.display)
        self.timer.start(1000)

        self.build_tray()
        self.resize(220, 100)
        self.central()

        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        # 透明处理,移动需要拖动数字
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.setMouseTracking(True)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

    def build_tray(self):
        trayIcon = QtGui.QSystemTrayIcon(self)
        trayIcon.setIcon(QtGui.QIcon('logo.png'))
        trayIcon.show()
        trayIcon.setToolTip('时钟')
        trayIcon.activated.connect(self.trayClick)

        menu = QtGui.QMenu()
        normalAction = menu.addAction('正常显示')
        miniAction = menu.addAction('最小化托盘')
        exitAction = menu.addAction('退出')
        normalAction.triggered.connect(self.showNormal)
        exitAction.triggered.connect(self.exit)
        miniAction.triggered.connect(self.showMinimized)

        trayIcon.setContextMenu(menu)

    def exit(self):
        # 不设置Visible为False,退出后TrayIcon不会刷新
        self.setVisible(False)
        sys.exit(0)

    def trayClick(self, reason):
        if reason == QtGui.QSystemTrayIcon.DoubleClick:
            self.showNormal()
            self.repaint()

    def display(self):
        current = QtCore.QTime.currentTime()
        self.hour.display(current.toString('HH:mm:ss'))

    def showNormal(self):
        super(LcdTime, self).showNormal()
        self.repaint()

    def central(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(screen.width() - size.width(), 0)


app = QtGui.QApplication(sys.argv)
lcd = LcdTime()
lcd.show()
sys.exit(app.exec_())