PyQT5例項 【2】 桌面LCD電子時鐘
阿新 • • 發佈:2018-12-09
今天,我要記錄的是用pyqt5寫的一個桌面電子時鐘,涉及到pyqt定時器,LCD顯示控制元件,pyqt5獲取時間等內容,單擊滑鼠右鍵會關閉此時鐘,效果圖如下圖
執行環境:Python35
開發環境: Eclipse-photon +PyDev
題外話: Eclipse真棒,Eclipse大法好
原始碼放在百度雲:
連結:https://pan.baidu.com/s/1_pE9N0CsDsfGFSFu_L4wzA 密碼:0fvp
首先,需要設計電子時鐘的類。姑且命名為DigitalClock,繼承自QLCDNumber
然後,要編寫main函式,main函式如下
''' Created on 2018-08-09 22:39 @author: Freedom ''' from PyQt5.QtWidgets import QApplication import sys from DigitalClock import DigitalClock def main(): app = QApplication(sys.argv) clock = DigitalClock(None) #新建電子時鐘 clock.show() #顯示電子時鐘 sys.exit(app.exec_()) #進入訊息迴圈 if __name__ == '__main__': main()
接下來是類DigitalClock的詳細程式碼
這是一個無邊框的窗體,
因此要使用函式setWindowFlags(Qt.FramelessWindowHint)來取消邊框,
但是,當邊框消失時,介面會無法移動或者關閉,因此,要重寫兩個函式來實現滑鼠拖動時鐘已經關閉時鐘,分別是
mousePressEvent(self, mouseEvent)
mouseMoveEvent(self, mouseEvent)
鑑於寫的是電子時鐘,因此,核心邏輯就是新建一個QTimer例項,即QT定時器物件,每隔1s鍾獲取一次當前的時間並以字串的形式顯示。當然,要呼叫QLCDNumber專用的顯示函式display才能有特效。
'''
Created on 2018年8月9日
@author: Freedom
'''
from PyQt5.QtWidgets import QLCDNumber
from PyQt5.Qt import QPoint, QPalette, QTimer, QTime, QRect
from PyQt5.QtCore import Qt
class DigitalClock(QLCDNumber):
def __init__(self, Parent=None):
'''
Constructor
'''
super().__init__(Parent)
self.__InitData() #初始化類的資料
self.__InitView() #初始化介面
def __InitData(self):
#初始化資料
self.__ShowColon = True #是否顯示時間如[12:07]中的冒號,用於冒號的閃爍
self.__dragPosition = QPoint(0,0) #用於儲存滑鼠相對於電子時鐘左上角的偏移值
self.__timer = QTimer(self) #新建一個定時器
#關聯timeout訊號和showTime函式,每當定時器過了指定時間間隔,就會呼叫showTime函式
self.__timer.timeout.connect(self.showTime)
self.__timer.start(1000) #設定定時間隔為1000ms即1s,並啟動定時器
def __InitView(self):
#初始化介面
palette = QPalette() #新建調色盤
palette.setColor(QPalette.Window, Qt.blue) #將調色盤中的窗體背景色設定為藍色
self.setPalette(palette) #在本窗體載入此調色盤
self.setWindowFlags(Qt.FramelessWindowHint) #設定窗體為無邊框模式
self.setWindowOpacity(0.5) #設定窗體的透明度為0.5
self.resize(200,60) #設定介面尺寸,寬150px,高60px
self.setNumDigits(8) #允許顯示8個字元 原因,自己數右邊幾個字元 【HH:MM:SS】
self.showTime() #初始化時間的顯示
def showTime(self):
#更新時間的顯示
time = QTime.currentTime() #獲取當前時間
time_text = time.toString(Qt.DefaultLocaleLongDate) #獲取HH:MM:SS格式的時間,在中國獲取後是這個格式,其他國家我不知道,如果有土豪願意送我去外國旅行的話我就可以試一試
#冒號閃爍
if self.__ShowColon == True:
self.__ShowColon = False
else:
time_text = time_text.replace(':',' ')
self.__ShowColon = True
self.display(time_text) #顯示時間
def mousePressEvent(self, mouseEvent):
#滑鼠按下事件
btn_code = mouseEvent.button()
if btn_code == Qt.LeftButton:
#如果是滑鼠左鍵按下
self.__dragPosition = mouseEvent.globalPos() - self.frameGeometry().topLeft()
print(self.__dragPosition)
mouseEvent.accept()
elif btn_code == Qt.RightButton:
print("It will close")
self.close() #滑鼠右鍵關閉時鐘
def mouseMoveEvent(self, mouseEvent):
#滑鼠移動事件
#在滑鼠拖動下,使用move函式移動電子時鐘
#move的引數是QPoint型別,可理解為形如(x,y)的向量
self.move(mouseEvent.globalPos()-self.__dragPosition)
mouseEvent.accept()