コード例 #1
0
ファイル: popup.py プロジェクト: kovidgoyal/vise
 def paint_background(self, painter):
     br = 12  # border_radius
     bw = 1  # border_width
     c = QColor('#fdfd96')
     p = QPainterPath()
     p.addRoundedRect(QRectF(self.rect()), br, br)
     painter.fillPath(p, c)
     p.addRoundedRect(
         QRectF(self.rect()).adjusted(bw, bw, -bw, -bw), br, br)
     painter.fillPath(p, QColor('black'))
コード例 #2
0
    def paintEvent(self, event):
        h = self.geometry().height()
        w = self.geometry().width()
        qp = QPainter()
        qp.begin(self)
        qp.setBrush(FILLBRUSH)
        qp.drawRect(self.rect())

        p = self.game.answering_player
        margin = self.__margin

        qp.setPen(SCOREPEN)
        qp.setFont(SCOREFONT)

        if self.winner:
            winnerrect = QRectF(0, NAMEHEIGHT + 2 * margin, w, 2 * NAMEHEIGHT)
            qp.drawText(
                winnerrect,
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                f"{self.winner.name} is the winner!",
            )
            return

        namerect = QRectF(0, margin, w, NAMEHEIGHT)
        qp.drawText(namerect,
                    Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                    p.name)

        if self.info_level > 0:
            answerrect = QRectF(0, NAMEHEIGHT + 2 * margin, w, 2 * NAMEHEIGHT)
            finalanswer = (p.finalanswer
                           if len(p.finalanswer.replace(" ", "")) > 0 else
                           "_________")
            qp.drawText(
                answerrect,
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                finalanswer,
            )

        if self.info_level > 1:
            wagerrect = QRectF(0, h - NAMEHEIGHT - margin, w, NAMEHEIGHT)
            qp.drawText(
                wagerrect,
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                f"{p.wager:,}",
            )
コード例 #3
0
    def mousePressEvent(self, event):
        if event.buttons() == Qt.MouseButton.LeftButton and (self.parent().parent().drawLineAction.isChecked() \
                 or self.parent().parent().obsTb.line_newRecButton.isChecked()) and self.gLineItem == None:

            self.setMouseTracking(True)
            p1 = self.mapToScene(int(event.position().x()),
                                 int(event.position().y()))
            self.gLineItem = self.scene().addLine(QLineF(p1, p1))
            r, g, b = np.random.choice(range(256), size=3)
            self.gLineItem.setPen(QPen(QColor(0, 0, 0), self.labelSize / 7))
            # self.gLineItem.setOpacity(0.25)

        elif event.buttons() == Qt.MouseButton.LeftButton and (self.parent().parent().maskGenAction.isChecked() \
                or self.parent().parent().obsTb.zone_newRecButton.isChecked()):
            self.setMouseTracking(True)
            p_clicked = self.mapToScene(int(event.position().x()),
                                        int(event.position().y()))
            if self.gPolyItem == None:
                self.currentPoly = QPolygonF([p_clicked])
                self.gPolyItem = self.scene().addPolygon(self.currentPoly)
                r, g, b = np.random.choice(range(256), size=3)
                self.gPolyItem.setPen(
                    QPen(QColor(r, g, b), self.labelSize / 10))
                self.gPolyItem.setBrush(QBrush(QColor(r, g, b, 40)))
            else:
                self.currentPoly.append(p_clicked)
                self.gPolyItem.setPolygon(self.currentPoly)

        elif event.buttons() == Qt.MouseButton.LeftButton and self.parent(
        ).parent().drawPointAction.isChecked():

            p = self.mapToScene(event.x(), event.y())
            pointBbx = QRectF()
            pointBbx.setSize(QSizeF(self.labelSize, self.labelSize))
            pointBbx.moveCenter(p)
            gPointItem = self.scene().addEllipse(
                pointBbx, QPen(Qt.GlobalColor.white, 0.5),
                QBrush(Qt.GlobalColor.black))
            self.unsavedPoints.append(gPointItem)
            self.scene().parent().drawPointAction.setChecked(False)
            self.unsetCursor()

        elif event.buttons() == Qt.MouseButton.LeftButton:  #RightButton:
            self.parent().parent().play()
コード例 #4
0
ファイル: MainWindow.py プロジェクト: BCN3D/Uranium
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self._background_color = QColor(204, 204, 204, 255)

        self.beforeRenderPassRecording.connect(
            self._render, type=Qt.ConnectionType.DirectConnection)

        self._mouse_device = QtMouseDevice(self)
        self._mouse_device.setPluginId("qt_mouse")
        self._key_device = QtKeyDevice()
        self._key_device.setPluginId("qt_key")
        self._previous_focus = None  # type: Optional["QQuickItem"]

        self._app = QCoreApplication.instance()

        # Remove previously added input devices (if any). This can happen if the window was re-loaded.
        self._app.getController().removeInputDevice("qt_mouse")
        self._app.getController().removeInputDevice("qt_key")

        self._app.getController().addInputDevice(self._mouse_device)
        self._app.getController().addInputDevice(self._key_device)
        self._app.getController().getScene().sceneChanged.connect(
            self._onSceneChanged)
        self._app.getController().activeViewChanged.connect(
            self._onActiveViewChanged)
        Selection.selectionChanged.connect(self._onSceneChanged)
        self._preferences = Application.getInstance().getPreferences()

        self._preferences.addPreference("general/window_width",
                                        self.DEFAULT_WINDOW_WIDTH)
        self._preferences.addPreference("general/window_height",
                                        self.DEFAULT_WINDOW_HEIGHT)
        self._preferences.addPreference("general/window_left",
                                        self.DEFAULT_WINDOW_LEFT)
        self._preferences.addPreference("general/window_top",
                                        self.DEFAULT_WINDOW_TOP)
        self._preferences.addPreference("general/window_state",
                                        Qt.WindowState.WindowNoState.value)
        self._preferences.addPreference("general/restore_window_geometry",
                                        True)

        restored_geometry = QRect(
            int(self._preferences.getValue("general/window_left")),
            int(self._preferences.getValue("general/window_top")),
            int(self._preferences.getValue("general/window_width")),
            int(self._preferences.getValue("general/window_height")))

        if not self._preferences.getValue("general/restore_window_geometry"):
            # Ignore whatever the preferences said.
            Logger.log(
                "i",
                "Not restoring window geometry from preferences because 'restore_window_geometry' is false"
            )
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        # Make sure restored geometry is not outside the currently available screens
        screen_found = False
        for screen in self._app.screens():
            if restored_geometry.intersects(screen.availableGeometry()):
                screen_found = True
                break

        if not screen_found:
            Logger.log(
                "w",
                "Could not restore to previous location on screen, since the sizes or number of monitors "
                "have changed since then")
            # Unable to find the screen that this window used to be on, so just use the defaults
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        self.setGeometry(restored_geometry)
        # Translate window state back to enum.
        try:
            window_state = int(
                self._preferences.getValue("general/window_state"))
        except ValueError:
            self._preferences.resetPreference("general/window_state")
            window_state = int(
                self._preferences.getValue("general/window_state"))

        if window_state == Qt.WindowState.WindowNoState.value:
            self.setWindowState(Qt.WindowState.WindowNoState)
        elif window_state == Qt.WindowState.WindowMaximized.value:
            self.setWindowState(Qt.WindowState.WindowMaximized)

        self._mouse_x = 0
        self._mouse_y = 0

        self._mouse_pressed = False

        self._viewport_rect = QRectF(0, 0, 1.0, 1.0)

        self.closing.connect(self.preClosing)

        Application.getInstance().setMainWindow(self)
        self._fullscreen = False

        self._full_render_required = True

        self._allow_resize = True
コード例 #5
0
ファイル: MainWindow.py プロジェクト: BCN3D/Uranium
class MainWindow(QQuickWindow):
    """QQuickWindow subclass that provides the main window."""
    DEFAULT_WINDOW_WIDTH = 1280
    DEFAULT_WINDOW_HEIGHT = 720
    DEFAULT_WINDOW_LEFT = 50
    DEFAULT_WINDOW_TOP = 50

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self._background_color = QColor(204, 204, 204, 255)

        self.beforeRenderPassRecording.connect(
            self._render, type=Qt.ConnectionType.DirectConnection)

        self._mouse_device = QtMouseDevice(self)
        self._mouse_device.setPluginId("qt_mouse")
        self._key_device = QtKeyDevice()
        self._key_device.setPluginId("qt_key")
        self._previous_focus = None  # type: Optional["QQuickItem"]

        self._app = QCoreApplication.instance()

        # Remove previously added input devices (if any). This can happen if the window was re-loaded.
        self._app.getController().removeInputDevice("qt_mouse")
        self._app.getController().removeInputDevice("qt_key")

        self._app.getController().addInputDevice(self._mouse_device)
        self._app.getController().addInputDevice(self._key_device)
        self._app.getController().getScene().sceneChanged.connect(
            self._onSceneChanged)
        self._app.getController().activeViewChanged.connect(
            self._onActiveViewChanged)
        Selection.selectionChanged.connect(self._onSceneChanged)
        self._preferences = Application.getInstance().getPreferences()

        self._preferences.addPreference("general/window_width",
                                        self.DEFAULT_WINDOW_WIDTH)
        self._preferences.addPreference("general/window_height",
                                        self.DEFAULT_WINDOW_HEIGHT)
        self._preferences.addPreference("general/window_left",
                                        self.DEFAULT_WINDOW_LEFT)
        self._preferences.addPreference("general/window_top",
                                        self.DEFAULT_WINDOW_TOP)
        self._preferences.addPreference("general/window_state",
                                        Qt.WindowState.WindowNoState.value)
        self._preferences.addPreference("general/restore_window_geometry",
                                        True)

        restored_geometry = QRect(
            int(self._preferences.getValue("general/window_left")),
            int(self._preferences.getValue("general/window_top")),
            int(self._preferences.getValue("general/window_width")),
            int(self._preferences.getValue("general/window_height")))

        if not self._preferences.getValue("general/restore_window_geometry"):
            # Ignore whatever the preferences said.
            Logger.log(
                "i",
                "Not restoring window geometry from preferences because 'restore_window_geometry' is false"
            )
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        # Make sure restored geometry is not outside the currently available screens
        screen_found = False
        for screen in self._app.screens():
            if restored_geometry.intersects(screen.availableGeometry()):
                screen_found = True
                break

        if not screen_found:
            Logger.log(
                "w",
                "Could not restore to previous location on screen, since the sizes or number of monitors "
                "have changed since then")
            # Unable to find the screen that this window used to be on, so just use the defaults
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        self.setGeometry(restored_geometry)
        # Translate window state back to enum.
        try:
            window_state = int(
                self._preferences.getValue("general/window_state"))
        except ValueError:
            self._preferences.resetPreference("general/window_state")
            window_state = int(
                self._preferences.getValue("general/window_state"))

        if window_state == Qt.WindowState.WindowNoState.value:
            self.setWindowState(Qt.WindowState.WindowNoState)
        elif window_state == Qt.WindowState.WindowMaximized.value:
            self.setWindowState(Qt.WindowState.WindowMaximized)

        self._mouse_x = 0
        self._mouse_y = 0

        self._mouse_pressed = False

        self._viewport_rect = QRectF(0, 0, 1.0, 1.0)

        self.closing.connect(self.preClosing)

        Application.getInstance().setMainWindow(self)
        self._fullscreen = False

        self._full_render_required = True

        self._allow_resize = True

    # This event is triggered before hideEvent(self, event) event and might prevent window closing if
    # does not pass the check, for example if USB printer is printing
    # The implementation is in Cura.qml
    preClosing = pyqtSignal("QQuickCloseEvent*", arguments=["close"])

    def setAllowResize(self, allow_resize: bool):
        if self._allow_resize != allow_resize:
            if not allow_resize:
                self.setMaximumHeight(self.height())
                self.setMinimumHeight(self.height())
                self.setMaximumWidth(self.width())
                self.setMinimumWidth(self.width())
            else:
                self.setMaximumHeight(16777215)
                self.setMinimumHeight(0)
                self.setMaximumWidth(16777215)
                self.setMinimumWidth(0)
            self._allow_resize = allow_resize

    @pyqtSlot()
    def toggleFullscreen(self):
        if self._fullscreen:
            self.setVisibility(
                QQuickWindow.Visibility.Windowed)  # Switch back to windowed
        else:
            self.setVisibility(
                QQuickWindow.Visibility.FullScreen)  # Go to fullscreen
        self._fullscreen = not self._fullscreen

    @pyqtSlot()
    def exitFullscreen(self):
        self.setVisibility(QQuickWindow.Visibility.Windowed)
        self._fullscreen = False

    def getBackgroundColor(self):
        return self._background_color

    def setBackgroundColor(self, color):
        self._background_color = color
        self._app.getRenderer().setBackgroundColor(color)

    backgroundColor = pyqtProperty(QColor,
                                   fget=getBackgroundColor,
                                   fset=setBackgroundColor)

    mousePositionChanged = pyqtSignal()

    @pyqtProperty(int, notify=mousePositionChanged)
    def mouseX(self):
        return self._mouse_x

    @pyqtProperty(int, notify=mousePositionChanged)
    def mouseY(self):
        return self._mouse_y

    def setViewportRect(self, rect):
        if rect != self._viewport_rect:
            self._viewport_rect = rect
            self._updateViewportGeometry(
                self.width() * self.devicePixelRatio(),
                self.height() * self.devicePixelRatio())
            self.viewportRectChanged.emit()

    viewportRectChanged = pyqtSignal()

    @pyqtProperty(QRectF, fset=setViewportRect, notify=viewportRectChanged)
    def viewportRect(self):
        return self._viewport_rect


#   Warning! Never reimplemented this as a QExposeEvent can cause a deadlock with QSGThreadedRender due to both trying
#   to claim the Python GIL.
#   def event(self, event):

    @pyqtSlot(QObject)
    def mousePressed(self, event):
        if event is None:
            return
        wrap_event = MouseEventWrapper(event.property("x"),
                                       event.property("y"),
                                       event.property("buttons"),
                                       event.property("button"),
                                       QEvent.Type.MouseButtonPress)
        self._mouse_pressed = True
        self._mouse_device.handleEvent(wrap_event)

    @pyqtSlot(QObject)
    def mouseMoved(self, event):
        if event is None:
            return
        wrap_event = MouseEventWrapper(event.property("x"),
                                       event.property("y"),
                                       event.property("buttons"),
                                       event.property("button"),
                                       QEvent.Type.MouseMove)
        self._mouse_device.handleEvent(wrap_event)

    @pyqtSlot(QObject)
    def wheel(self, event):
        if event is None:
            return
        wrap_event = MouseEventWrapper(event.property("x"),
                                       event.property("y"),
                                       event.property("buttons"),
                                       event.property("button"),
                                       QEvent.Type.Wheel,
                                       event.property("angleDelta"))
        self._mouse_device.handleEvent(wrap_event)

    @pyqtSlot(QObject)
    def mouseReleased(self, event):
        if event is None:
            return
        wrap_event = MouseEventWrapper(event.property("x"),
                                       event.property("y"),
                                       event.property("buttons"),
                                       event.property("button"),
                                       QEvent.Type.MouseButtonRelease)
        self._mouse_pressed = False
        self._mouse_device.handleEvent(wrap_event)

    def mousePressEvent(self, event):
        event.setAccepted(False)
        super().mousePressEvent(event)
        if event.isAccepted():
            return

        if self.activeFocusItem(
        ) is not None and self.activeFocusItem() != self._previous_focus:
            self.activeFocusItem().setFocus(False)

        self._previous_focus = self.activeFocusItem()

    def mouseMoveEvent(self, event):
        event.setAccepted(False)
        self._mouse_x = event.pos().x()
        self._mouse_y = event.pos().y()

        if self._mouse_pressed:
            self.mousePositionChanged.emit()

        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        event.setAccepted(False)
        super().mouseReleaseEvent(event)
        if event.isAccepted():
            return

    def keyPressEvent(self, event):
        super().keyPressEvent(event)
        if event.isAccepted():
            return

        self._key_device.handleEvent(event)

    def keyReleaseEvent(self, event):
        super().keyReleaseEvent(event)
        if event.isAccepted():
            return

        self._key_device.handleEvent(event)

    def wheelEvent(self, event):
        event.setAccepted(False)
        super().wheelEvent(event)

    def moveEvent(self, event):
        QMetaObject.invokeMethod(self, "_onWindowGeometryChanged",
                                 Qt.ConnectionType.QueuedConnection)

    def resizeEvent(self, event):
        super().resizeEvent(event)

        win_w = event.size().width() * self.devicePixelRatio()
        win_h = event.size().height() * self.devicePixelRatio()

        self._updateViewportGeometry(win_w, win_h)

        QMetaObject.invokeMethod(self, "_onWindowGeometryChanged",
                                 Qt.ConnectionType.QueuedConnection)

    def hideEvent(self, event):
        if Application.getInstance().getMainWindow() == self:
            Application.getInstance().windowClosed()

    renderCompleted = Signal(type=Signal.Queued)

    def _render(self):
        self.beginExternalCommands()
        if self._full_render_required:
            renderer = self._app.getRenderer()
            view = self._app.getController().getActiveView()
            renderer.beginRendering()
            view.beginRendering()
            renderer.render()
            view.endRendering()
            renderer.endRendering()
            self._full_render_required = False
            self.renderCompleted.emit()
        else:
            self._app.getRenderer().reRenderLast()
        self.endExternalCommands()

    def _onSceneChanged(self, object=None):
        self._full_render_required = True
        self.update()

    def _onActiveViewChanged(self):
        self._full_render_required = True
        self.update()

    @pyqtSlot()
    def _onWindowGeometryChanged(self):
        # Do not store maximised window geometry, but store state instead
        # Using windowState instead of isMaximized is a workaround for QTBUG-30085
        if self.windowState() == Qt.WindowState.WindowNoState:
            self._preferences.setValue("general/window_width", self.width())
            self._preferences.setValue("general/window_height", self.height())
            self._preferences.setValue("general/window_left", self.x())
            self._preferences.setValue("general/window_top", self.y())

        if self.windowState() in (Qt.WindowState.WindowNoState,
                                  Qt.WindowState.WindowMaximized):
            self._preferences.setValue("general/window_state",
                                       self.windowState().value)

    def _updateViewportGeometry(self, width: int, height: int) -> None:
        view_width = round(width * self._viewport_rect.width())
        view_height = round(height * self._viewport_rect.height())

        for camera in self._app.getController().getScene().getAllCameras():
            camera.setWindowSize(width, height)

            if camera.getAutoAdjustViewPort():
                camera.setViewportSize(view_width, view_height)

        self._app.getRenderer().setViewportSize(view_width, view_height)
        self._app.getRenderer().setWindowSize(width, height)
コード例 #6
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setBrush(FILLBRUSH)
        parent = self.parent()
        pheight = parent.geometry().height()
        height = pheight * (1 - SCOREHEIGHT)
        width = height / CELLRATIO
        if not self.board.final:
            # Normal board
            for x in range(self.board.size[0]):
                for y in range(-1, self.board.size[1]):
                    rel_pos = (
                        x * self.cellsize[0] + BORDERWIDTH / 2,
                        (y + 1) * self.cellsize[1],
                    )
                    cell = (x, y)
                    qp.setPen(BORDERPEN)
                    qp.setBrush(FILLBRUSH)
                    cell_rect = QRectF(*rel_pos, *self.cellsize)
                    text_rect = QRectF(cell_rect)
                    text_rect.setX(cell_rect.x() + TEXTPADDING)
                    text_rect.setWidth(cell_rect.width() - 2 * TEXTPADDING)
                    qp.drawRect(cell_rect)
                    if y == -1:
                        # Categories
                        qp.setPen(CATPEN)
                        qp.setFont(CATFONT)
                        qp.drawText(
                            text_rect,
                            Qt.TextFlag.TextWordWrap
                            | Qt.AlignmentFlag.AlignCenter,
                            self.board.categories[x],
                        )
                    else:
                        # Questions
                        q = self.board.get_question(*cell)
                        if not q in self.game.completed_questions:
                            qp.setPen(MONPEN)
                            qp.setFont(MONFONT)
                            if not self.board.dj:
                                monies = gp.money1
                            else:
                                monies = gp.money2
                            qp.drawText(
                                text_rect,
                                Qt.TextFlag.TextWordWrap
                                | Qt.AlignmentFlag.AlignCenter,
                                "$" + str(q.value),
                            )
        else:
            # Final jeopardy
            qp.setBrush(FILLBRUSH)
            qp.drawRect(self.rect())
            qp.setPen(CATPEN)
            qp.setFont(QUFONT)

            qurect = self.rect().adjusted(QUMARGIN, QUMARGIN, -2 * QUMARGIN,
                                          -2 * QUMARGIN)

            qp.drawText(
                qurect,
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                self.board.categories[0],
            )
コード例 #7
0
 def __scorerect(self, i):
     w = self.geometry().width()
     h = self.geometry().height()
     sw = w // len(self.game.players)
     return QRectF(sw * i, DIVIDERWIDTH, sw, h - NAMEHEIGHT - DIVIDERWIDTH)
コード例 #8
0
    def paintEvent(self, event):
        h = self.geometry().height()
        w = self.geometry().width()
        qp = QPainter()
        qp.begin(self)
        qp.setBrush(FILLBRUSH)
        qp.drawRect(QRectF(0, DIVIDERWIDTH, w, h))

        qp.setBrush(DIVIDERBRUSH)
        dividerrect = QRectF(0, 0, w, DIVIDERWIDTH)
        qp.drawRect(dividerrect)

        # Light dividers
        num_lights = 9
        light_width = w // num_lights
        light_padding = 3
        ungrouped_rects = [
            QRect(
                light_width * i + light_padding,
                light_padding,
                light_width - 2 * light_padding,
                DIVIDERWIDTH - 2 * light_padding,
            ) for i in range(num_lights)
        ]
        grouped_rects = [[
            rect for j, rect in enumerate(ungrouped_rects)
            if abs(num_lights // 2 - j) == i
        ] for i in range(5)]
        qp.setBrush(LIGHTBRUSH)
        qp.setPen(LIGHTPEN)
        for i, rects in enumerate(grouped_rects):
            if i < self.__light_level:
                for rect in rects:
                    qp.drawRect(rect)

        margin = 50
        players = self.game.players
        sw = w // len(players)

        if self.game.current_round.final:
            highlighted_players = [
                p for p in players if p not in self.game.wagered
            ]
        else:
            highlighted_players = []
        ap = self.game.answering_player
        if ap:
            highlighted_players.append(ap)

        for i, p in enumerate(players):
            if p.score < 0:
                qp.setPen(HOLEPEN)
            else:
                qp.setPen(SCOREPEN)

            qp.setFont(SCOREFONT)
            qp.drawText(
                self.__scorerect(i),
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                f"{p.score:,}",
            )

            namerect = QRectF(sw * i, h - NAMEHEIGHT, sw, NAMEHEIGHT)
            qp.setFont(NAMEFONT)
            qp.setPen(NAMEPEN)
            if p in highlighted_players:
                qp.setBrush(HIGHLIGHTBRUSH)
                qp.drawRect(namerect)
                qp.setPen(HIGHLIGHTPEN)
            qp.drawText(
                namerect,
                Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter,
                p.name,
            )
コード例 #9
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, index)
     hovering = index.data(HOVER_ROLE) is True
     painter.save()
     painter.setRenderHint(QPainter.RenderHint.Antialiasing)
     painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
     rect = option.rect
     is_current = index.data(Qt.ItemDataRole.FontRole) is not None
     if not hovering and is_current:
         qpp = QPainterPath()
         qpp.addRoundedRect(QRectF(rect), 6, 6)
         painter.fillPath(qpp, self.current_background)
     icon_rect = QRect(rect.left() + self.MARGIN,
                       rect.top() + self.MARGIN, ICON_SIZE, ICON_SIZE)
     left = icon_rect.right() + 2 * self.MARGIN
     text_rect = QRect(left, icon_rect.top(),
                       rect.width() - left + rect.left(),
                       icon_rect.height())
     mark = index.data(MARK_ROLE)
     if hovering or mark:
         text_rect.adjust(0, 0, -text_rect.height(), 0)
     text = index.data(DISPLAY_ROLE) or ''
     muted = index.data(MUTED_ROLE)
     if muted:
         mc = get_icon('volume-off.svg').pixmap(ICON_SIZE, ICON_SIZE)
         painter.drawPixmap(
             QRect(text_rect.left(), text_rect.top(), ICON_SIZE,
                   text_rect.height()), mc, mc.rect())
         text_rect.adjust(ICON_SIZE, 0, 0, 0)
     font = index.data(Qt.ItemDataRole.FontRole)
     if font:
         painter.setFont(font)
     text_flags = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft | Qt.TextFlag.TextSingleLine
     text = elided_text(text, font, text_rect.width(), 'right')
     if option.state & QStyle.StateFlag.State_Selected:
         painter.setPen(QPen(self.highlighted_text))
     painter.drawText(text_rect, text_flags, text)
     if mark:
         hrect = QRect(text_rect.right(), text_rect.top(),
                       text_rect.height(), text_rect.height())
         painter.fillRect(hrect, QColor('#ffffaa'))
         painter.drawText(hrect, Qt.AlignmentFlag.AlignCenter, mark)
     elif hovering:
         hrect = QRect(text_rect.right(), text_rect.top(),
                       text_rect.height(), text_rect.height())
         close_hover = index.data(CLOSE_HOVER_ROLE) is True
         if close_hover:
             pen = painter.pen()
             pen.setColor(QColor('red'))
             painter.setPen(pen)
         painter.drawText(hrect, Qt.AlignmentFlag.AlignCenter, '✖ ')
     if index.data(LOADING_ROLE) > 0:
         lc = self.frames[self.frame_number]
         painter.drawPixmap(icon_rect.topLeft(), lc)
     else:
         icurl = index.data(URL_ROLE)
         if icurl == WELCOME_URL:
             icon = welcome_icon()
         elif icurl == DOWNLOADS_URL:
             icon = get_icon(DOWNLOAD_ICON_NAME)
         else:
             icon = index.data(DECORATION_ROLE)
         icon.paint(painter, icon_rect)
     painter.restore()
コード例 #10
0
    def generate_itemGroup(self, xs, ys, label, type):
        gItemGroup = QGraphicsItemGroup()

        pointBbx = QRectF()
        pointBbx.setSize(QSizeF(self.gView.labelSize, self.gView.labelSize))

        textLabel = QGraphicsTextItem(label)

        if len(xs) == 1:
            pointBbx.moveCenter(QPointF(xs[0], ys[0]))
            textLabel.setPos(xs[0] - (textLabel.boundingRect().width() / 2),
                             ys[0] - (textLabel.boundingRect().height() / 2))

            pointShape = QGraphicsEllipseItem(pointBbx)
            shapeColor = Qt.GlobalColor.white
            textColor = Qt.GlobalColor.black
            tooltip = 'P{}:{}'
        elif len(xs) == 2:
            pointBbx.moveCenter(QPointF(xs[1], ys[1]))
            textLabel.setPos(xs[1] - (textLabel.boundingRect().width() / 2),
                             ys[1] - (textLabel.boundingRect().height() / 2))

            r, g, b = np.random.choice(range(256), size=3)
            line_item = QGraphicsLineItem(xs[0], ys[0], xs[1], ys[1])
            line_item.setPen(
                QPen(QColor(r, g, b, 128), self.gView.labelSize / 6))
            gItemGroup.addToGroup(line_item)

            # line_end = QGraphicsEllipseItem(xs[1], ys[1],
            #                                 int(self.gView.labelSize/3), int(self.gView.labelSize/3))
            # line_end.setPen(QPen(QColor(r, g, b), 0.5))
            # line_end.setBrush(QBrush(QColor(r, g, b)))
            # gItemGroup.addToGroup(line_end)

            pointShape = QGraphicsEllipseItem(pointBbx)
            shapeColor = QColor(r, g, b, 128)
            textColor = Qt.GlobalColor.black
            tooltip = 'L{}:{}'
            # textLabel.setRotation(np.arctan((ys[1] - ys[0])/(xs[1] - xs[0]))*(180/3.14))
        else:
            pointBbx.moveCenter(QPointF(np.mean(xs), np.mean(ys)))
            textLabel.setPos(
                np.mean(xs) - (textLabel.boundingRect().width() / 2),
                np.mean(ys) - (textLabel.boundingRect().height() / 2))

            points = [QPointF(x, y) for x, y in zip(xs, ys)]
            polygon = QPolygonF(points)
            r, g, b = np.random.choice(range(256), size=3)
            zone_item = QGraphicsPolygonItem(polygon)
            zone_item.setPen(QPen(QColor(r, g, b), self.gView.labelSize / 10))
            zone_item.setBrush(QBrush(QColor(r, g, b, 40)))
            gItemGroup.addToGroup(zone_item)

            pointShape = QGraphicsRectItem(pointBbx)
            shapeColor = Qt.GlobalColor.darkBlue
            textColor = Qt.GlobalColor.white
            tooltip = 'Z{}:{}'

        pointShape.setPen(QPen(Qt.GlobalColor.white, 0.5))
        pointShape.setBrush(QBrush(shapeColor))
        # self.gView.scene().addEllipse(pointBbx, QPen(Qt.white, 0.5), QBrush(Qt.black))
        gItemGroup.setToolTip(tooltip.format(label, type))
        gItemGroup.addToGroup(pointShape)

        labelFont = QFont()
        labelFont.setPointSize(round(self.gView.labelSize / 2))
        labelFont.setBold(True)

        textLabel.setFont(labelFont)
        textLabel.setDefaultTextColor(textColor)

        gItemGroup.addToGroup(textLabel)
        return gItemGroup