Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
From PyQt4.QtGui import *
From PyQt4.QtCore import *
From PyQt4.Qt import *
Class CLabel (QWidget ):
SignalLabelPress = pyqtSignal ()
Def _ init _ (self, parent = None ):
Super (CLabel, self). _ init _ (parent)
Self. initVariable ()
Self. initSetupUi ()
# Self. m_mouseEnterFlag = False
# Self. m_mousePressFlag = True
# Pointer members
# Self. m_pLabelIcon = QLabel (self)
# Self. m_pLabelText = QLabel (self)
Def setPixmap (self, pixmap ):
Self. m_pLabelIcon.setPixmap (pixmap. scaled (QSize (30, 30), Qt. KeepAspectRatio, Qt. SmoothTransformation ))
Def setText (self, text ):
Self. m_pLabelText.setText (text)
Def setMouseEnterFlag (self, flag ):
Self. m_mouseEnterFlag = flag
Self. update ()
Def setMousePressFlag (self, flag ):
Self. m_mousePressFlag = flag
Self. update ()
Def enterEvent (self, event ):
If (~ Self. getMousePressFlag ()):
Self. setMouseEnterFlag (True)
Self. setCursor (Qt. PointingHandCursor)
Def leaveEvent (self, event ):
Self. setMouseEnterFlag (False)
Def mousePressEvent (self, e ):
If (e. button () = Qt. LeftButton ):
Self. setMousePressFlag (True)
Self. signalLabelPress. emit ()
Def paintEvent (self, e ):
Painter = QPainter (self)
If (self. getMouseEnterFlag ()):
Self. paintWidget (50, painter)
Elif (self. getMousePressFlag ()):
Self. paintWidget (80, painter)
QWidget. paintEvent (self, e)
Def initVariable (self ):
Self. setMouseEnterFlag (False)
Self. setMousePressFlag (False)
Def initSetupUi (self ):
Self. createFrame ()
Self. createWidget ()
Self. createLayout ()
Def createFrame (self ):
Self. setStyleSheet ("QWidget background: transparentborder: 0 pxcolor: whitefont-weight: boldfont-size: 16px ")
Def createWidget (self ):
Self. m_pLabelIcon = QLabel (self)
Self. m_pLabelText = QLabel (self)
Def createLayout (self ):
Self. m_pHLayout = QHBoxLayout ()
Self. m_pHLayout.setSpacing (10)
Self. m_pHLayout.setContentsMargins (QMargins (5, 0, 5, 0 ))
Self. m_pHLayout.addWidget (self. m_pLabelIcon)
Self. m_pHLayout.addWidget (self. m_pLabelText)
Self. m_pHLayout.addStretch ()
Self. setLayout (self. m_pHLayout)
Def paintWidget (self, transparency, device): # QPainter *
# Self. pen = QPen (Qt. NoBrush)
# Self. pen. setWidth (1)
Device. setPen (Qt. NoPen)
Self. linear = QLinearGradient (QPointF (self. rect (). topLeft (), QPointF (self. rect (). bottomLeft ()))
Self. linear. setColorAt (0, QColor (255,255,255, transparency ))
Self. brush = QBrush (self. linear)
Device. setBrush (self. brush)
Device. drawRoundedRect (self. rect (), 2, 2)
Def getMouseEnterFlag (self ):
Return self. m_mouseEnterFlag
Def getMousePressFlag (self ):
Return self. m_mousePressFlag
If _ name _ = '_ main __':
Import sys
App = QApplication (sys. argv)
Label = CLabel ()
Label. show ()
Sys.exit(app.exe c _())