label.py 10.5 KB
Newer Older
之一Yo's avatar
之一Yo 已提交
1
# coding:utf-8
2
from typing import List, Union
之一Yo's avatar
之一Yo 已提交
3

之一Yo's avatar
之一Yo 已提交
4
from PyQt5.QtCore import Qt, pyqtProperty, QPoint, pyqtSignal, QSize, QRectF
5 6
from PyQt5.QtGui import (QPixmap, QPainter, QPalette, QColor, QFont, QImage, QPainterPath,
                         QImageReader, QBrush, QMovie)
7
from PyQt5.QtWidgets import QLabel, QWidget, QApplication
之一Yo's avatar
之一Yo 已提交
8 9 10 11

from ...common.overload import singledispatchmethod
from ...common.font import setFont, getFont
from ...common.config import qconfig, isDarkTheme
12 13


之一Yo's avatar
之一Yo 已提交
14 15
class PixmapLabel(QLabel):
    """ Label for high dpi pixmap """
16 17 18

    def __init__(self, parent=None):
        super().__init__(parent)
之一Yo's avatar
之一Yo 已提交
19
        self.__pixmap = QPixmap()
之一Yo's avatar
之一Yo 已提交
20

之一Yo's avatar
之一Yo 已提交
21 22 23
    def setPixmap(self, pixmap: QPixmap):
        self.__pixmap = pixmap
        self.setFixedSize(pixmap.size())
之一Yo's avatar
之一Yo 已提交
24 25
        self.update()

之一Yo's avatar
之一Yo 已提交
26 27
    def pixmap(self):
        return self.__pixmap
之一Yo's avatar
之一Yo 已提交
28

之一Yo's avatar
之一Yo 已提交
29 30
    def paintEvent(self, e):
        if self.__pixmap.isNull():
31
            return super().paintEvent(e)
之一Yo's avatar
之一Yo 已提交
32 33

        painter = QPainter(self)
之一Yo's avatar
之一Yo 已提交
34 35 36 37
        painter.setRenderHints(QPainter.Antialiasing |
                               QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)
        painter.drawPixmap(self.rect(), self.__pixmap)
之一Yo's avatar
之一Yo 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55


class FluentLabelBase(QLabel):
    """ Fluent label base class """

    @singledispatchmethod
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self._init()

    @__init__.register
    def _(self, text: str, parent: QWidget = None):
        self.__init__(parent)
        self.setText(text)

    def _init(self):
        self.setFont(self.getFont())
        self.setTextColor()
56 57
        qconfig.themeChanged.connect(
            lambda: self.setTextColor(self.lightColor, self.darkColor))
之一Yo's avatar
之一Yo 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70
        return self

    def getFont(self):
        raise NotImplementedError

    def setTextColor(self, light=QColor(0, 0, 0), dark=QColor(255, 255, 255)):
        """ set the text color of label

        Parameters
        ----------
        light, dark: QColor | Qt.GlobalColor | str
            text color in light/dark mode
        """
71 72
        self._lightColor = QColor(light)
        self._darkColor = QColor(dark)
之一Yo's avatar
之一Yo 已提交
73 74 75 76 77 78

        palette = self.palette()
        color = self.darkColor if isDarkTheme() else self.lightColor
        palette.setColor(QPalette.WindowText, color)
        self.setPalette(palette)

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    @pyqtProperty(QColor)
    def lightColor(self):
        return self._lightColor

    @lightColor.setter
    def lightColor(self, color: QColor):
        self.setTextColor(color, self.darkColor)

    @pyqtProperty(QColor)
    def darkColor(self):
        return self._darkColor

    @darkColor.setter
    def darkColor(self, color: QColor):
        self.setTextColor(self.lightColor, color)

    @pyqtProperty(int)
    def pixelFontSize(self):
        return self.font().pixelSize()

    @pixelFontSize.setter
    def pixelFontSize(self, size: int):
        font = self.font()
        font.setPixelSize(size)
        self.setFont(font)

    @pyqtProperty(bool)
    def strikeOut(self):
        return self.font().strikeOut()

    @strikeOut.setter
    def strikeOut(self, isStrikeOut: bool):
        font = self.font()
        font.setStrikeOut(isStrikeOut)
        self.setFont(font)

    @pyqtProperty(bool)
    def underline(self):
        return self.font().underline()

    @underline.setter
    def underline(self, isUnderline: bool):
        font = self.font()
        font.setStyle()
        font.setUnderline(isUnderline)
        self.setFont(font)

之一Yo's avatar
之一Yo 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

class CaptionLabel(FluentLabelBase):
    """ Caption text label """

    def getFont(self):
        return getFont(12)


class BodyLabel(FluentLabelBase):
    """ Body text label """

    def getFont(self):
        return getFont(14)


class StrongBodyLabel(FluentLabelBase):
    """ Strong body text label """

    def getFont(self):
        return getFont(14, QFont.DemiBold)


class SubtitleLabel(FluentLabelBase):
    """ Sub title text label """

    def getFont(self):
        return getFont(20, QFont.DemiBold)


class TitleLabel(FluentLabelBase):
    """ Sub title text label """

    def getFont(self):
        return getFont(28, QFont.DemiBold)


class LargeTitleLabel(FluentLabelBase):
    """ Large title text label """

    def getFont(self):
        return getFont(40, QFont.DemiBold)


class DisplayLabel(FluentLabelBase):
    """ Display text label """

    def getFont(self):
        return getFont(68, QFont.DemiBold)
174 175 176 177 178


class ImageLabel(QLabel):
    """ Image label """

之一Yo's avatar
之一Yo 已提交
179 180
    clicked = pyqtSignal()

181 182 183 184
    @singledispatchmethod
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.image = QImage()
185
        self.setBorderRadius(0, 0, 0, 0)
之一Yo's avatar
之一Yo 已提交
186
        self._postInit()
187

188 189 190 191
    @__init__.register
    def _(self, image: str, parent=None):
        self.__init__(parent)
        self.setImage(image)
之一Yo's avatar
之一Yo 已提交
192
        self._postInit()
193 194 195 196 197

    @__init__.register
    def _(self, image: QImage, parent=None):
        self.__init__(parent)
        self.setImage(image)
之一Yo's avatar
之一Yo 已提交
198
        self._postInit()
199 200 201 202 203

    @__init__.register
    def _(self, image: QPixmap, parent=None):
        self.__init__(parent)
        self.setImage(image)
之一Yo's avatar
之一Yo 已提交
204 205 206 207
        self._postInit()

    def _postInit(self):
        pass
208

209 210 211 212 213 214
    def _onFrameChanged(self, index: int):
        self.image = self.movie().currentImage()
        self.update()

    def setBorderRadius(self, topLeft: int, topRight: int, bottomLeft: int, bottomRight: int):
        """ set the border radius of image """
215 216 217 218
        self._topLeftRadius = topLeft
        self._topRightRadius = topRight
        self._bottomLeftRadius = bottomLeft
        self._bottomRightRadius = bottomRight
219 220 221 222
        self.update()

    def setImage(self, image: Union[str, QPixmap, QImage] = None):
        """ set the image of label """
223
        self.image = image or QImage()
224 225 226 227 228 229 230 231 232 233

        if isinstance(image, str):
            reader = QImageReader(image)
            if reader.supportsAnimation():
                self.setMovie(QMovie(image))
            else:
                self.image = reader.read()
        elif isinstance(image, QPixmap):
            self.image = image.toImage()

之一Yo's avatar
之一Yo 已提交
234
        self.setFixedSize(self.image.size())
235
        self.update()
之一Yo's avatar
之一Yo 已提交
236

237 238 239 240
    def scaledToWidth(self, width: int):
        if self.isNull():
            return

241 242
        h = int(width / self.image.width() * self.image.height())
        self.setFixedSize(width, h)
243 244

        if self.movie():
245
            self.movie().setScaledSize(QSize(width, h))
246 247 248 249 250

    def scaledToHeight(self, height: int):
        if self.isNull():
            return

251 252
        w = int(height / self.image.height() * self.image.width())
        self.setFixedSize(w, height)
253 254

        if self.movie():
255
            self.movie().setScaledSize(QSize(w, height))
256 257 258 259

    def isNull(self):
        return self.image.isNull()

之一Yo's avatar
之一Yo 已提交
260 261 262 263
    def mouseReleaseEvent(self, e):
        super().mouseReleaseEvent(e)
        self.clicked.emit()

264 265 266
    def setPixmap(self, pixmap: QPixmap):
        self.setImage(pixmap)

之一Yo's avatar
之一Yo 已提交
267 268 269
    def pixmap(self) -> QPixmap:
        return QPixmap.fromImage(self.image)

270 271 272 273 274 275
    def setMovie(self, movie: QMovie):
        super().setMovie(movie)
        self.movie().start()
        self.image = self.movie().currentImage()
        self.movie().frameChanged.connect(self._onFrameChanged)

276 277 278 279 280
    def paintEvent(self, e):
        if self.isNull():
            return

        painter = QPainter(self)
281
        painter.setRenderHints(QPainter.Antialiasing)
282 283

        path = QPainterPath()
284
        w, h = self.width(), self.height()
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

        # top line
        path.moveTo(self.topLeftRadius, 0)
        path.lineTo(w - self.topRightRadius, 0)

        # top right arc
        d = self.topRightRadius * 2
        path.arcTo(w - d, 0, d, d, 90, -90)

        # right line
        path.lineTo(w, h - self.bottomRightRadius)

        # bottom right arc
        d = self.bottomRightRadius * 2
        path.arcTo(w - d, h - d, d, d, 0, -90)

        # bottom line
        path.lineTo(self.bottomLeftRadius, h)

        # bottom left arc
        d = self.bottomLeftRadius * 2
        path.arcTo(0, h - d, d, d, -90, -90)

        # left line
        path.lineTo(0, self.topLeftRadius)

        # top left arc
        d = self.topLeftRadius * 2
        path.arcTo(0, 0, d, d, -180, -90)

        # draw image
316 317 318
        image = self.image.scaled(
            self.size()*self.devicePixelRatioF(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)

319
        painter.setPen(Qt.NoPen)
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        painter.setClipPath(path)
        painter.drawImage(self.rect(), image)

    @pyqtProperty(int)
    def topLeftRadius(self):
        return self._topLeftRadius

    @topLeftRadius.setter
    def topLeftRadius(self, radius: int):
        self.setBorderRadius(radius, self.topRightRadius, self.bottomLeftRadius, self.bottomRightRadius)

    @pyqtProperty(int)
    def topRightRadius(self):
        return self._topRightRadius

    @topRightRadius.setter
    def topRightRadius(self, radius: int):
        self.setBorderRadius(self.topLeftRadius, radius, self.bottomLeftRadius, self.bottomRightRadius)

    @pyqtProperty(int)
    def bottomLeftRadius(self):
        return self._bottomLeftRadius

    @bottomLeftRadius.setter
    def bottomLeftRadius(self, radius: int):
        self.setBorderRadius(self.topLeftRadius, self.topRightRadius, radius, self.bottomRightRadius)

    @pyqtProperty(int)
    def bottomRightRadius(self):
        return self._bottomRightRadius

    @bottomRightRadius.setter
    def bottomRightRadius(self, radius: int):
之一Yo's avatar
之一Yo 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        self.setBorderRadius(
            self.topLeftRadius, self.topRightRadius, self.bottomLeftRadius, radius)


class AvatarWidget(ImageLabel):
    """ Avatar widget """

    def _postInit(self):
        self.setRadius(48)

    def getRadius(self):
        return self._radius

    def setRadius(self, radius: int):
        self._radius = radius
        self.setFixedSize(2*radius, 2*radius)
        self.update()

    def paintEvent(self, e):
        if self.isNull():
            return

        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing)

        # center crop image
        image = self.image.scaled(
            self.size()*self.devicePixelRatioF(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation) # type: QImage

        iw, ih = image.width(), image.height()
        d = self.getRadius() * 2 * self.devicePixelRatioF()
        x, y = (iw - d) / 2, (ih - d) / 2
之一Yo's avatar
之一Yo 已提交
385
        image = image.copy(int(x), int(y), int(d), int(d))
之一Yo's avatar
之一Yo 已提交
386 387 388 389 390 391 392 393 394 395

        # draw image
        path = QPainterPath()
        path.addEllipse(QRectF(self.rect()))

        painter.setPen(Qt.NoPen)
        painter.setClipPath(path)
        painter.drawImage(self.rect(), image)

    radius = pyqtProperty(int, getRadius, setRadius)