picker_base.py 15.4 KB
Newer Older
之一Yo's avatar
之一Yo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
# coding:utf-8
from typing import Iterable, List

from PyQt5.QtCore import QEvent, Qt, pyqtSignal, QSize, QRectF, QPoint, QPropertyAnimation, QEasingCurve
from PyQt5.QtGui import QColor, QPainter, QCursor, QRegion
from PyQt5.QtWidgets import (QApplication, QWidget, QFrame, QVBoxLayout, QHBoxLayout,
                             QGraphicsDropShadowEffect, QSizePolicy, QPushButton, QListWidgetItem)

from ..widgets.cycle_list_widget import CycleListWidget
from ..widgets.button import TransparentToolButton
from ...common.icon import FluentIcon
from ...common.style_sheet import FluentStyleSheet, themeColor, isDarkTheme


class SeparatorWidget(QWidget):
    """ Separator widget """

    def __init__(self, orient: Qt.Orientation, parent=None):
        super().__init__(parent=parent)
        if orient == Qt.Horizontal:
            self.setFixedHeight(1)
        else:
            self.setFixedWidth(1)

        self.setAttribute(Qt.WA_StyledBackground)
        FluentStyleSheet.TIME_PICKER.apply(self)


class ItemMaskWidget(QWidget):
    """ Item mask widget """

    def __init__(self, listWidgets: List[CycleListWidget], parent=None):
        super().__init__(parent=parent)
        self.listWidgets = listWidgets
        self.setFixedHeight(37)
        FluentStyleSheet.TIME_PICKER.apply(self)

    def paintEvent(self, e):
        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing |
                               QPainter.TextAntialiasing)

        # draw background
        painter.setPen(Qt.NoPen)
        painter.setBrush(themeColor())
        painter.drawRoundedRect(self.rect().adjusted(4, 0, -3, 0), 5, 5)

        # draw text
        painter.setPen(Qt.black if isDarkTheme() else Qt.white)
        painter.setFont(self.font())
        w, h = 0, self.height()
        for i, p in enumerate(self.listWidgets):
            painter.save()

            # draw first item's text
            x = p.itemSize.width()//2 + 4 + self.x()
            item1 = p.itemAt(QPoint(x, self.y() + 6))
            if not item1:
                painter.restore()
                continue

            iw = item1.sizeHint().width()
            y = p.visualItemRect(item1).y()
            painter.translate(w, y - self.y() + 7)
            self._drawText(item1, painter, 0)

            # draw second item's text
            item2 = p.itemAt(self.pos() + QPoint(x, h - 6))
            self._drawText(item2, painter, h)

            painter.restore()
            w += (iw + 8)  # margin: 0 4px;

    def _drawText(self, item: QListWidgetItem, painter: QPainter, y: int):
        align = item.textAlignment()
        w, h = item.sizeHint().width(), item.sizeHint().height()
        if align & Qt.AlignLeft:
            rect = QRectF(15, y, w, h)      # padding-left: 11px
        elif align & Qt.AlignRight:
            rect = QRectF(4, y, w-15, h)    # padding-right: 11px
        elif align & Qt.AlignCenter:
            rect = QRectF(4, y, w, h)

        painter.drawText(rect, align, item.text())


class PickerColumn:
    """ Picker column """

    def __init__(self, name: str, items: list, width: int, align=Qt.AlignLeft):
        self.name = name
        self.items = items
        self.width = width
        self.align = align
之一Yo's avatar
之一Yo 已提交
95 96 97 98 99 100 101 102 103 104
        self._value = None   # type: str
        self.isVisible = True

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        self._value = str(v)
之一Yo's avatar
之一Yo 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 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


class PickerBase(QPushButton):
    """ Picker base class """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.columns = []   # type: List[PickerColumn]
        self.columnMap = {}
        self.buttons = []   # type: List[QPushButton]

        self.hBoxLayout = QHBoxLayout(self)

        self.hBoxLayout.setSpacing(0)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.setSizeConstraint(QHBoxLayout.SetFixedSize)

        FluentStyleSheet.TIME_PICKER.apply(self)
        self.clicked.connect(self._showPanel)

    def addColumn(self, name: str, items: Iterable, width: int, align=Qt.AlignCenter):
        """ add column

        Parameters
        ----------
        name: str
            the name of column

        items: Iterable
            the items of column

        width: int
            the width of column

        align: Qt.AlignmentFlag
            the text alignment of button
        """
        if name in self.columnMap:
            return

        # create column
        column = PickerColumn(name, list(items), width, align)
        self.columns.append(column)
        self.columnMap[name] = column

        # create button
        button = QPushButton(name, self)
        button.setFixedSize(width, 30)
        button.setObjectName('pickerButton')
        button.setProperty('hasBorder', False)
        button.setAttribute(Qt.WA_TransparentForMouseEvents)

        self.hBoxLayout.addWidget(button, 0, Qt.AlignLeft)
        self.buttons.append(button)

之一Yo's avatar
之一Yo 已提交
160
        self._setButtonAlignment(button, align)
之一Yo's avatar
之一Yo 已提交
161 162 163 164 165 166

        # update the style of buttons
        for btn in self.buttons[:-1]:
            btn.setProperty('hasBorder', True)
            btn.setStyle(QApplication.style())

之一Yo's avatar
之一Yo 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    def _setButtonAlignment(self, button: QPushButton, align=Qt.AlignCenter):
        """ set the text alignment of button """
        if align == Qt.AlignLeft:
            button.setProperty('align', 'left')
        elif align == Qt.AlignRight:
            button.setProperty('align', 'right')
        else:
            button.setProperty('align', 'center')

    def setColumnAlignment(self, index: int, align=Qt.AlignCenter):
        """ set the text alignment of specified column """
        if not 0 <= index < len(self.columns):
            return

        self.columns[index].align = align
        self._setButtonAlignment(self.buttons[index], align)

    def setColumnVisible(self, index: int, isVisible: bool):
        """ set the text alignment of specified column """
        if not 0 <= index < len(self.columns):
            return

        self.columns[index].isVisible = isVisible
        self.buttons[index].setVisible(isVisible)

之一Yo's avatar
之一Yo 已提交
192
    def value(self):
之一Yo's avatar
之一Yo 已提交
193
        return [c.value for c in self.columns if c.isVisible]
之一Yo's avatar
之一Yo 已提交
194 195 196 197 198 199 200 201 202 203

    def setColumnValue(self, index: int, value):
        if not 0 <= index < len(self.columns):
            return

        value = str(value)
        self.columns[index].value = value
        self.buttons[index].setText(value)
        self._setButtonProperty('hasValue', True)

之一Yo's avatar
之一Yo 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    def setColumn(self, index: int, name: str, items: Iterable, width: int, align=Qt.AlignCenter):
        """ set column

        Parameters
        ----------
        index: int
            the index of column

        name: str
            the name of column

        items: Iterable
            the items of column

        width: int
            the width of column

        align: Qt.AlignmentFlag
            the text alignment of button
        """
        if not 0 <= index < len(self.columns):
            return

        column = self.columns[index]
        self.columnMap.pop(column.name)

        column = PickerColumn(name, items, width, align)
        self.columns[index] = column
        self.columnMap[name] = column

        self.buttons[index].setText(name)
        self.buttons[index].setFixedWidth(width)
        self._setButtonAlignment(self.buttons[index], align)

    def clearColumns(self):
        """ clear columns """
        self.columns.clear()
        self.columnMap.clear()
        while self.buttons:
            btn = self.buttons.pop()
            btn.deleteLater()

之一Yo's avatar
之一Yo 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    def enterEvent(self, e):
        self._setButtonProperty('enter', True)

    def leaveEvent(self, e):
        self._setButtonProperty('enter', False)

    def mousePressEvent(self, e):
        self._setButtonProperty('pressed', True)
        super().mousePressEvent(e)

    def mouseReleaseEvent(self, e):
        self._setButtonProperty('pressed', False)
        super().mouseReleaseEvent(e)

    def _setButtonProperty(self, name, value):
        """ send event to picker buttons """
        for button in self.buttons:
            button.setProperty(name, value)
            button.setStyle(QApplication.style())

    def _showPanel(self):
        """ show panel """
        panel = PickerPanel(self)
        for column in self.columns:
之一Yo's avatar
之一Yo 已提交
270 271
            if column.isVisible:
                panel.addColumn(column.items, column.width, column.align)
之一Yo's avatar
之一Yo 已提交
272 273

        panel.setValue(self.value())
之一Yo's avatar
之一Yo 已提交
274

之一Yo's avatar
之一Yo 已提交
275
        panel.confirmed.connect(self._onConfirmed)
之一Yo's avatar
之一Yo 已提交
276 277 278
        panel.columnValueChanged.connect(
            lambda i, v: self._onColumnValueChanged(panel, i, v))

之一Yo's avatar
之一Yo 已提交
279 280 281 282 283 284
        panel.exec(self.mapToGlobal(QPoint(0, -37*4)))

    def _onConfirmed(self, value: list):
        for i, v in enumerate(value):
            self.setColumnValue(i, v)

之一Yo's avatar
之一Yo 已提交
285 286 287 288
    def _onColumnValueChanged(self, panel, index: int, value: str):
        """ column value changed slot """
        pass

之一Yo's avatar
之一Yo 已提交
289 290 291 292 293

class PickerPanel(QWidget):
    """ picker panel """

    confirmed = pyqtSignal(list)
之一Yo's avatar
之一Yo 已提交
294
    columnValueChanged = pyqtSignal(int, str)
之一Yo's avatar
之一Yo 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 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 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

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.itemHeight = 37
        self.listWidgets = []   # type: List[CycleListWidget]

        self.view = QFrame(self)
        self.itemMaskWidget = ItemMaskWidget(self.listWidgets, self)
        self.hSeparatorWidget = SeparatorWidget(Qt.Horizontal, self.view)
        self.yesButton = TransparentToolButton(FluentIcon.ACCEPT, self.view)
        self.cancelButton = TransparentToolButton(FluentIcon.CLOSE, self.view)

        self.hBoxLayout = QHBoxLayout(self)
        self.listLayout = QHBoxLayout()
        self.buttonLayout = QHBoxLayout()
        self.vBoxLayout = QVBoxLayout(self.view)

        self.__initWidget()

    def __initWidget(self):
        self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint |
                            Qt.NoDropShadowWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.setShadowEffect()
        self.yesButton.setIconSize(QSize(16, 16))
        self.cancelButton.setIconSize(QSize(13, 13))
        self.yesButton.setFixedHeight(33)
        self.cancelButton.setFixedHeight(33)

        self.hBoxLayout.setContentsMargins(12, 8, 12, 20)
        self.hBoxLayout.addWidget(self.view, 1, Qt.AlignCenter)
        self.hBoxLayout.setSizeConstraint(QHBoxLayout.SetMinimumSize)

        self.vBoxLayout.setSpacing(0)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.addLayout(self.listLayout, 1)
        self.vBoxLayout.addWidget(self.hSeparatorWidget)
        self.vBoxLayout.addLayout(self.buttonLayout, 1)
        self.vBoxLayout.setSizeConstraint(QVBoxLayout.SetMinimumSize)

        self.buttonLayout.setSpacing(6)
        self.buttonLayout.setContentsMargins(3, 3, 3, 3)
        self.buttonLayout.addWidget(self.yesButton)
        self.buttonLayout.addWidget(self.cancelButton)
        self.yesButton.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.cancelButton.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.yesButton.clicked.connect(self._fadeOut)
        self.yesButton.clicked.connect(
            lambda: self.confirmed.emit(self.value()))
        self.cancelButton.clicked.connect(self._fadeOut)

        self.view.setObjectName('view')
        FluentStyleSheet.TIME_PICKER.apply(self)

    def setShadowEffect(self, blurRadius=30, offset=(0, 8), color=QColor(0, 0, 0, 30)):
        """ add shadow to dialog """
        self.shadowEffect = QGraphicsDropShadowEffect(self.view)
        self.shadowEffect.setBlurRadius(blurRadius)
        self.shadowEffect.setOffset(*offset)
        self.shadowEffect.setColor(color)
        self.view.setGraphicsEffect(None)
        self.view.setGraphicsEffect(self.shadowEffect)

    def addColumn(self, items: Iterable, width: int, align=Qt.AlignCenter):
        """ add one column to view

        Parameters
        ----------
        items: Iterable[Any]
            the items to be added

        width: int
            the width of item

        align: Qt.AlignmentFlag
            the text alignment of item
        """
        if self.listWidgets:
            self.listLayout.addWidget(SeparatorWidget(Qt.Vertical))

        w = CycleListWidget(items, QSize(width, self.itemHeight), align, self)
        w.vScrollBar.valueChanged.connect(self.itemMaskWidget.update)

之一Yo's avatar
之一Yo 已提交
382 383 384 385
        N = len(self.listWidgets)
        w.currentItemChanged.connect(
            lambda i, n=N: self.columnValueChanged.emit(n, i.text()))

之一Yo's avatar
之一Yo 已提交
386 387 388 389 390 391 392 393 394
        self.listWidgets.append(w)
        self.listLayout.addWidget(w)

    def resizeEvent(self, e):
        self.itemMaskWidget.resize(self.view.width()-3, self.itemHeight)
        m = self.hBoxLayout.contentsMargins()
        self.itemMaskWidget.move(m.left()+2, m.top() + 148)

    def value(self):
之一Yo's avatar
之一Yo 已提交
395
        """ return the value of columns """
之一Yo's avatar
之一Yo 已提交
396 397 398
        return [i.currentItem().text() for i in self.listWidgets]

    def setValue(self, value: list):
之一Yo's avatar
之一Yo 已提交
399 400 401 402
        """ set the value of columns """
        if len(value) != len(self.listWidgets):
            return

之一Yo's avatar
之一Yo 已提交
403 404 405
        for v, w in zip(value, self.listWidgets):
            w.setSelectedItem(v)

之一Yo's avatar
之一Yo 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    def columnValue(self, index: int) -> str:
        """ return the value of specified column """
        if not 0 <= index < len(self.listWidgets):
            return

        return self.listWidgets[index].currentItem().text()

    def setColumnValue(self, index: int, value: str):
        """ set the value of specified column """
        if not 0 <= index < len(self.listWidgets):
            return

        self.listWidgets[index].setSelectedItem(value)

    def column(self, index: int):
        """ return the list widget of specified column """
        return self.listWidgets[index]

之一Yo's avatar
之一Yo 已提交
424
    def exec(self, pos, ani=True):
之一Yo's avatar
之一Yo 已提交
425
        """ show panel
之一Yo's avatar
之一Yo 已提交
426 427 428 429 430 431 432 433 434 435 436 437

        Parameters
        ----------
        pos: QPoint
            pop-up position

        ani: bool
            Whether to show pop-up animation
        """
        if self.isVisible():
            return

之一Yo's avatar
之一Yo 已提交
438 439 440
        # show before running animation, or the height calculation will be wrong
        self.show()

之一Yo's avatar
之一Yo 已提交
441
        rect = QApplication.screenAt(QCursor.pos()).availableGeometry()
之一Yo's avatar
之一Yo 已提交
442
        w, h = self.width() + 5, self.height()
之一Yo's avatar
之一Yo 已提交
443 444
        pos.setX(
            min(pos.x() - self.layout().contentsMargins().left(), rect.right() - w))
之一Yo's avatar
之一Yo 已提交
445
        pos.setY(max(rect.top(), min(pos.y() - 4, rect.bottom() - h + 5)))
之一Yo's avatar
之一Yo 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        self.move(pos)

        if not ani:
            return

        self.isExpanded = False
        self.ani = QPropertyAnimation(self.view, b'windowOpacity', self)
        self.ani.valueChanged.connect(self._onAniValueChanged)
        self.ani.setStartValue(0)
        self.ani.setEndValue(1)
        self.ani.setDuration(150)
        self.ani.setEasingCurve(QEasingCurve.OutQuad)
        self.ani.start()

    def _onAniValueChanged(self, opacity):
        m = self.layout().contentsMargins()
        w = self.view.width() + m.left() + m.right() + 120
        h = self.view.height() + m.top() + m.bottom() + 12
        if not self.isExpanded:
            y = int(h / 2 * (1 - opacity))
            self.setMask(QRegion(0, y, w, h-y*2))
        else:
            y = int(h / 3 * (1 - opacity))
            self.setMask(QRegion(0, y, w, h-y*2))

    def _fadeOut(self):
        self.isExpanded = True
        self.ani = QPropertyAnimation(self, b'windowOpacity', self)
        self.ani.valueChanged.connect(self._onAniValueChanged)
        self.ani.finished.connect(self.deleteLater)
        self.ani.setStartValue(1)
        self.ani.setEndValue(0)
        self.ani.setDuration(150)
        self.ani.setEasingCurve(QEasingCurve.OutQuad)
        self.ani.start()