コード例 #1
0
    def draw_board(self):
        """
         Description
        -------------
         - Paint all of the tiles for the Trivial Purfuit board

         Parameters
        -------------
         (1) event: The event signal (QEvent.Type.Paint).

         NOTE/TODO
        -------------
         (1) Don't be lazy and brute force..
         (2) Run the current board layout by the team
        """
        painter = QPainter(self)
        painter.setPen(QPen(Qt.black, 5, Qt.SolidLine))

        x = 0
        y = 0

        # The board is drawn from left to right.
        for row in range(self.num_row_tiles):
            for col in range(self.num_col_tiles):

                if self.is_roll_again_tile(row, col):
                    painter.setBrush(
                        QBrush(self.roll_again_tile_color, Qt.SolidPattern))
                    painter.drawRect(x, y, self.board_tile_width,
                                     self.board_tile_height)

                elif self.is_person_tile(row, col):
                    painter.setBrush(
                        QBrush(self.person_tile_color, Qt.SolidPattern))
                    painter.drawRect(x, y, self.board_tile_width,
                                     self.board_tile_height)

                elif self.is_holiday_tile(row, col):
                    painter.setBrush(
                        QBrush(self.holiday_tile_color, Qt.SolidPattern))
                    painter.drawRect(x, y, self.board_tile_width,
                                     self.board_tile_height)

                elif self.is_event_tile(row, col):
                    painter.setBrush(
                        QBrush(self.events_tile_color, Qt.SolidPattern))
                    painter.drawRect(x, y, self.board_tile_width,
                                     self.board_tile_height)

                elif self.is_place_tile(row, col):
                    painter.setBrush(
                        QBrush(self.places_tile_color, Qt.SolidPattern))
                    painter.drawRect(x, y, self.board_tile_width,
                                     self.board_tile_height)
                # end if

                # TODO: Add image for the center tile and HQ tiles
                '''
                elif self.isHQTile(row, col):
                    tmp_painter.setBrush(QBrush(self.places_tile_color, Qt.SolidPattern))
                    tmp_painter.drawRect(x, y, self.board_tile_width, self.board_tile_height)
                '''
                # Update to x-coordinate for next tile
                x = x + self.board_tile_width
            # end for

            # Reset (x,y) starting coordinates for next row and columns
            y = y + self.board_tile_height
            x = 0

        # end for
        self.board_initialized = True
コード例 #2
0
 def print(self):
     printer = QPrinter()
     dialog = QPrintDialog(printer)
     if dialog.exec() == QDialog.Accepted:
         painter = QPainter(printer)
         self.graphicsView.render(painter)
コード例 #3
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.drawPixmap(self.rect(), QPixmap(":/images/background.png"))
     QWidget.paintEvent(self, event)
コード例 #4
0
    def saveSceneToFile(self, filename, imageformat, transparent, rastsize):
        '''
        Save the current scene to the named file.
        
        If imageformat is empty or None, the format is guessed from
        the filename extension.

        If transparent is False, the entire scene is initialized
        to the last clearing color.

        If given, rastsize is the pixels size of the saved image.
        If rastsize is not given, the saved image will be saved
        at the current scaled image size.  
        '''
        # This could be called when there is no image present.
        # If this is the case, ignore the call.
        if (self.__sceneimage == None):
            return
        if not imageformat:
            # Guess the image format from the filename extension
            # This is only done to silently change gif to png
            fileext = (os.path.splitext(filename)[1]).lower()
            if fileext == '.gif':
                myformat = 'gif'
            else:
                # let QImage figure out the format
                myformat = None
        else:
            myformat = imageformat.lower()

        if myformat == 'gif':
            # Silently convert gif filename and format to png
            myformat = 'png'
            myfilename = os.path.splitext(filename)[0] + ".png"
        else:
            myfilename = filename
        # set the cursor and status message to indicate a save is happending
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.statusBar().showMessage(self.tr("Saving image"))
        try:
            if rastsize:
                imagewidth = int(rastsize.width() + 0.5)
                imageheight = int(rastsize.height() + 0.5)
            else:
                imagewidth = int(self.__scenewidth * self.__scalefactor + 0.5)
                imageheight = int(self.__sceneheight * self.__scalefactor +
                                  0.5)
            myimage = QImage(QSize(imagewidth, imageheight),
                             QImage.Format_ARGB32_Premultiplied)
            # Initialize the image
            if not transparent:
                # Clear the image with self.__lastclearcolor
                fillint = self.__helper.computeARGB32PreMultInt(
                    self.__lastclearcolor)
            else:
                fillint = 0
            myimage.fill(fillint)
            # draw the scaled scene to this QImage
            mypainter = QPainter(myimage)
            trgrect = QRectF(0.0, 0.0, float(imagewidth), float(imageheight))
            srcrect = QRectF(0.0, 0.0, float(self.__scenewidth),
                             float(self.__sceneheight))
            mypainter.drawImage(trgrect, self.__sceneimage, srcrect,
                                Qt.AutoColor)
            mypainter.end()
            # save the image to file
            if not myimage.save(myfilename, myformat):
                raise ValueError("Unable to save the plot as " + myfilename)
        finally:
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()
コード例 #5
0
 def pixmap(self, size, mode=None, state=None):
     pm = QPixmap(size)
     pm.fill(Qt.transparent)
     self.paint(QPainter(pm), QRect(QPoint(0, 0), size), mode, state)
     return pm
コード例 #6
0
 def paintEvent(self, _) -> None:
     """Paint the current picture and all before it."""
     painter = QPainter(self)
     for i in range(self.current):
         x, y, image = self.map[i]
         painter.drawPixmap(x, y, image)
コード例 #7
0
ファイル: NodeWidget.py プロジェクト: zsh2020/Ryven
 def paintEvent(self, event):  # just to enable stylesheets
     o = QStyleOption()
     o.initFrom(self)
     p = QPainter(self)
     self.style().drawPrimitive(QStyle.PE_Widget, o, p, self)
コード例 #8
0
ファイル: Mp4EventHandler.py プロジェクト: xuyi/pyrdp
 def notifyImage(self, x: int, y: int, img: QImage, w: int, h: int):
     p = QPainter(self._buffer)
     p.drawImage(x, y, img, 0, 0, w, h)
コード例 #9
0
ファイル: __init__.py プロジェクト: tba-dev/tbautils
 def paintEvent(self, ev):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(Qt.NoPen)
     painter.setBrush(QBrush(QColor(255, 205, 42)))
     painter.drawRoundedRect(self.rect(), 10.0, 10.0)
コード例 #10
0
    def paintEvent(self, event: QPaintEvent) -> None:
        assert self.__parent_widget is not None

        painter = QPainter(self)

        indicator_pen = QPen(QColor(0x20, 0x20, 0x20))
        indicator_pen.setWidth(2)

        boundary_pen = QPen(QColor(0x20, 0x20, 0x20))
        boundary_pen.setWidth(4)

        INDICATOR_WIDTH = 10.0

        resolution = self.__parent_widget.resolution
        x = self.__parent_widget.argument
        upper = self.__parent_widget.upper_bound
        lower = self.__parent_widget.lower_bound
        maximum_value = self.__parent_widget.maximum_value
        minimum_value = self.__parent_widget.minimum_value

        original_to_scaled_converter = lambda x: np.divide(
            x - lower, upper - lower)
        scaled_to_original_converter = lambda x_scaled: np.multiply(
            x_scaled, upper - lower) + lower

        x_scaled = original_to_scaled_converter(x)

        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.TextAntialiasing)

        w = event.rect().width()
        h = event.rect().height()

        # Draw gradation
        gradation_width = int(w / min(resolution, w))
        for i in range(int(gradation_width / 2), w, gradation_width):
            x_scaled_temp = np.copy(x_scaled)
            x_scaled_temp[self.__target_dimension] = float(i) / float(w - 1)
            value = self.__parent_widget.calculate_value(
                scaled_to_original_converter(x_scaled_temp))

            # Normalize the value into [0, 1]
            value = (value - minimum_value) / (maximum_value - minimum_value)
            if hasattr(math, "isfinite"):  # Python 3.2 or later
                value = value if math.isfinite(value) else 0.5
            else:
                value = value if not (math.isnan(value)
                                      or math.isinf(value)) else 0.5

            # Get mapped color
            cmap = cm.get_cmap(name="viridis")
            rgba = cmap(value)
            color = QColor(int(rgba[0] * 255), int(rgba[1] * 255),
                           int(rgba[2] * 255))

            # Draw
            painter.fillRect(i - gradation_width / 2, 0, gradation_width * 2,
                             h, color)

        # Draw current position
        indicator_position = x_scaled[self.__target_dimension] * float(w)
        indicator_rect = QRectF(indicator_position - INDICATOR_WIDTH / 2.0,
                                0.0, INDICATOR_WIDTH, float(h))
        painter.setPen(indicator_pen)
        painter.drawRect(indicator_rect)

        # Draw boundary
        painter.setPen(boundary_pen)
        painter.drawRect(event.rect())
コード例 #11
0
 def paintEvent(self, event):
     painter = QPainter(self)
     pixmap = QPixmap('misc/sponsor.jpg')
     painter.drawPixmap(self.rect(), pixmap)
コード例 #12
0
ファイル: Canvas.py プロジェクト: robert-clayton/ILYA
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # TODO: Use QPainterPath's arcTo function to do this in a single draw
        # Draw background
        painter.save()
        self.brush.setColor(ThemeManager.BG_L2_QC)
        self.brush.setStyle(Qt.SolidPattern)
        painter.setBrush(self.brush)
        painter.setPen(Qt.NoPen)
        painter.drawRect(0, 0, self.size().width() / 2, self.size().height()) # Left Side
        painter.drawRect(0, 0, self.size().width(), self.size().height() / 2) # Top Side
        painter.drawRoundedRect(self.rect(), ThemeManager.CURVE, ThemeManager.CURVE)
        painter.restore()

        # If image is set
        if self.imageData:
            if self.imageData.isValid():
                # Find xy offsets
                self.dx = self.size().width()  - self.scaledImage.size().width()  if self.size().width()  - self.scaledImage.size().width()  else self.scaledImage.size().width()  - self.size().width()
                self.dy = self.size().height() - self.scaledImage.size().height() if self.size().height() - self.scaledImage.size().height() else self.scaledImage.size().height() - self.size().height()

                # Paint rescaled image
                painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
                painter.drawPixmap(self.dx / 2, self.dy / 2, self.scaledImage)

                # Paint in-progress box
                if self.drawingRect:
                    painter.save()
                    x, x2, y, y2 = self.drawingRect
                    # Convert % to xy coords, account for off by one error
                    x  = (x * self.scaledImage.size().width() + self.dx / 2) - 1
                    y  = (y * self.scaledImage.size().height() + self.dy / 2) - 1
                    x2 = (x2 * self.scaledImage.size().width() + self.dx / 2) - 2
                    y2 = (y2 * self.scaledImage.size().height() + self.dy / 2) - 2

                    # Setup painter's brush and pen colors
                    self.brush.setColor(ThemeManager.ACCENT_LOW_OPACITY_QC)
                    self.brush.setStyle(Qt.SolidPattern)
                    self.pen.setColor(ThemeManager.ACCENT_QC)
                    painter.setBrush(self.brush)
                    painter.setPen(self.pen)
                    painter.drawRect(QRect(QPoint(x, y), QPoint(x2, y2)))
                    painter.restore()

                # Paint existing boxes
                for box in self.boxes:
                    painter.save()

                    # Draw box's rect
                    x, x2, y, y2 = box.getRect()
                    x  = (x * self.scaledImage.size().width() + self.dx / 2) - 1
                    y  = (y * self.scaledImage.size().height() + self.dy / 2) - 1
                    x2 = (x2 * self.scaledImage.size().width() + self.dx / 2) - 1
                    y2 = (y2 * self.scaledImage.size().height() + self.dy / 2) - 2
                    self.brush.setColor(ThemeManager.ACCENT_VLOW_OPACITY_QC)
                    self.brush.setStyle(Qt.SolidPattern)
                    self.pen.setColor(ThemeManager.ACCENT_QC)
                    painter.setBrush(self.brush)
                    painter.setPen(self.pen)
                    painter.drawRect(QRect(QPoint(x, y), QPoint(x2, y2)))

                    # Draw label BG
                    painter.setPen(Qt.NoPen)
                    self.brush.setColor(ThemeManager.ACCENT_QC)
                    painter.setBrush(self.brush)
                    labelWidth = QFontMetrics(self.font).width(box.getLabel())
                    labelHeight = QFontMetrics(self.font).height()
                    painter.drawRect(x, y, labelWidth + 4, labelHeight)

                    # Draw label
                    self.pen.setColor(ThemeManager.BLACK_QC)
                    painter.setPen(self.pen)
                    painter.drawText(x + 2, y + 11, box.getLabel())
                    painter.restore()

        if self.message:
            painter.save()
            font = QFont('Arial', 20)
            messageWidth = QFontMetrics(font).width(self.message)
            painter.setFont(font)
            self.pen.setColor(ThemeManager.ACCENT_QC)
            painter.setPen(self.pen)
            painter.drawText((self.width() - messageWidth) / 2, self.height() * .9, self.message)
            painter.restore()
コード例 #13
0
    def paintEvent(self, paint_event):
        self.m_width = self.width()
        self.m_height = self.height()

        if self.channel1Enable:
            self.Channel1PaintList = []
            self.Channel1PaintList2 = []
        if self.channel2Enable:
            self.Channel2PaintList = []
            self.Channel2PaintList2 = []
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing, True)

        pen = QPen(Qt.white, 1, Qt.SolidLine)
        qp.setPen(pen)
        qp.translate(0, self.m_height / 2)
        qp.drawLine(0, 0, self.m_width, 0)
        qp.drawLine(self.m_width / 2, self.m_height / 2, self.m_width / 2,
                    -self.m_height / 2)

        pen.setStyle(Qt.DashLine)
        pen.setWidth(1)
        qp.setPen(pen)
        qp.drawLine(0, -self.m_height / 4, self.m_width, -self.m_height / 4)
        qp.drawLine(0, self.m_height / 4, self.m_width, self.m_height / 4)
        qp.drawLine(self.m_width / 4, -self.m_height / 2, self.m_width / 4,
                    self.m_height / 2)
        qp.drawLine(self.m_width * 3 / 4, -self.m_height / 2,
                    self.m_width * 3 / 4, self.m_height / 2)

        pen.setStyle(Qt.SolidLine)
        pen.setWidth(5)
        qp.setPen(pen)
        for i in range(1, 10):
            qp.drawLine(i * (self.m_width / 10), self.m_height / 2,
                        i * (self.m_width / 10), self.m_height / 2 - 1)

        pen.setWidth(2)
        pen.setStyle(Qt.SolidLine)
        pen.setColor(QColor(200, 100, 100))
        qp.setPen(pen)
        self.unit = float(self.m_height) * 0.4 / ADCVALUEMAX
        self.paintPointMax = self.m_width

        if self.channel1Enable:
            if self.scaleRatio == 1:
                self.Channel1PaintList = copy.copy(self.Channel1List)
            else:
                self.Channel1PaintList2 = copy.copy(self.Channel1List)
                for i in range(0, len(self.Channel1PaintList2),
                               self.scaleRatio):
                    self.Channel1PaintList.append(self.Channel1PaintList2[i])
            # print "self.Channel1PaintList:", self.Channel1PaintList
            self.Channel1PaintListLen = len(self.Channel1PaintList)

        if self.channel2Enable:
            if self.scaleRatio == 1:
                self.Channel2PaintList = copy.copy(self.Channel2List)
            else:
                self.Channel2PaintList2 = copy.copy(self.Channel2List)
                for i in range(0, len(self.Channel2PaintList2),
                               self.scaleRatio):
                    self.Channel2PaintList.append(self.Channel2PaintList2[i])
            # print "self.Channel2PaintList:", self.Channel2PaintList
            self.Channel2PaintListLen = len(self.Channel2PaintList)

        if self.channel1Enable:
            if self.Channel1PaintListLen == 0:
                qp.drawLine(0, 0, self.m_width, self.m_height / 2)
            elif self.Channel1PaintListLen >= self.paintPointMax:
                if self.dragEnable is True:
                    if len(
                            self.Channel1PaintList
                    ) - self.dragBias - self.dragBias_t < self.paintPointMax:
                        # self.dragBias_t = len(self.Channel1PaintList) - self.paintPointMax - self.dragBias
                        self.dragBias_t = 0
                        self.dragBias = len(
                            self.Channel1PaintList) - self.paintPointMax
                    if self.dragBias + self.dragBias_t < 0:
                        self.dragBias_t = 0
                        self.dragBias = 0

                for i in range(0, self.paintPointMax):
                    qp.drawLine(
                        self.paintPointMax - 1 - i,
                        -self.Channel1PaintList[self.Channel1PaintListLen - 1 -
                                                i - self.dragBias -
                                                self.dragBias_t] * self.unit,
                        self.paintPointMax - 2 - i,
                        -self.Channel1PaintList[self.Channel1PaintListLen - 2 -
                                                i - self.dragBias -
                                                self.dragBias_t] * self.unit)
                    # print "dragBias,dragBias_t:", self.dragBias,self.dragBias_t

            else:
                for i in range(self.Channel1PaintListLen - 1, 0, -1):

                    qp.drawLine(
                        i + self.paintPointMax - self.Channel1PaintListLen,
                        -self.Channel1PaintList[i] * self.unit,
                        i + self.paintPointMax - self.Channel1PaintListLen - 1,
                        -self.Channel1PaintList[i - 1] * self.unit)
                    # qp.drawPoint(i, - self.Channel1PaintList[i] * self.unit)

        if self.channel2Enable:
            pen.setColor(QColor(0, 200, 255))
            qp.setPen(pen)
            if self.Channel2PaintListLen == 0:
                qp.drawLine(0, 0, self.m_width, self.m_height / 2)
            elif self.Channel2PaintListLen >= self.paintPointMax:
                if self.dragEnable is True:
                    if len(
                            self.Channel2PaintList
                    ) - self.dragBias - self.dragBias_t < self.paintPointMax:
                        # self.dragBias_t = len(self.Channel2PaintList) - self.paintPointMax - self.dragBias
                        self.dragBias_t = 0
                        self.dragBias = len(
                            self.Channel2PaintList) - self.paintPointMax
                    if self.dragBias + self.dragBias_t < 0:
                        self.dragBias_t = 0
                        self.dragBias = 0

                for i in range(0, self.paintPointMax):
                    qp.drawLine(
                        self.paintPointMax - 1 - i,
                        -self.Channel2PaintList[self.Channel2PaintListLen - 1 -
                                                i - self.dragBias -
                                                self.dragBias_t] * self.unit,
                        self.paintPointMax - 2 - i,
                        -self.Channel2PaintList[self.Channel2PaintListLen - 2 -
                                                i - self.dragBias -
                                                self.dragBias_t] * self.unit)
                    # print "dragBias,dragBias_t:", self.dragBias,self.dragBias_t

            else:
                for i in range(self.Channel2PaintListLen - 1, 0, -1):

                    qp.drawLine(
                        i + self.paintPointMax - self.Channel2PaintListLen,
                        -self.Channel2PaintList[i] * self.unit,
                        i + self.paintPointMax - self.Channel2PaintListLen - 1,
                        -self.Channel2PaintList[i - 1] * self.unit)
                    # qp.drawPoint(i, - self.Channel2PaintList[i] * self.unit)

        qp.setFont(QFont("NEW ROMAN TIME", 8))
        pen.setWidth(1)
        pen.setStyle(Qt.SolidLine)
        pen.setColor(Qt.yellow)
        qp.setPen(pen)
        qp.drawLine(self.dx, -self.m_height / 2, self.dx, self.m_height / 2)
        self.period = self.scaleRatio * 1000 / self.frequency  # unit:ms

        pen.setColor(QColor(200, 100, 100))
        qp.setPen(pen)

        if self.channel1Enable:
            if self.Channel1PaintListLen - (self.m_width - self.dx) >= 0:
                qp.drawText(
                    self.dx + 5, self.dy - self.m_height / 2 - 20, "time= -" +
                    str(self.period * (self.m_width - self.dx) + self.period *
                        (self.dragBias + self.dragBias_t)) + "ms")
                qp.drawText(
                    self.dx + 5, self.dy - self.m_height / 2, "volatge= " +
                    str(self.Channel1PaintList[self.Channel1PaintListLen -
                                               (self.m_width - self.dx) -
                                               self.dragBias -
                                               self.dragBias_t]) + "mV")
            else:
                qp.drawText(self.dx + 5, self.dy - self.m_height / 2, str(0))

        if self.channel2Enable:
            pen.setColor(QColor(0, 200, 255))
            qp.setPen(pen)
            if self.Channel2PaintListLen - (self.m_width - self.dx) >= 0:
                qp.drawText(
                    self.dx + 5, self.dy - self.m_height / 2 + 20, "time= -" +
                    str(self.period * (self.m_width - self.dx) + self.period *
                        (self.dragBias + self.dragBias_t)) + "ms")
                qp.drawText(
                    self.dx + 5, self.dy - self.m_height / 2 + 40,
                    "volatge= " +
                    str(self.Channel2PaintList[self.Channel2PaintListLen -
                                               (self.m_width - self.dx) -
                                               self.dragBias -
                                               self.dragBias_t]) + "mV")
            else:
                qp.drawText(self.dx + 5, self.dy - self.m_height / 2, str(0))
コード例 #14
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.translate(self.width() / 2, self.height() / 2)
     painter.drawEllipse(-5, -5, 20, 20)
コード例 #15
0
 def paintEvent(self, event):
     clientRect = QRect(QPoint(0, 0), self.size())
     painter = QPainter(self)
     painter.fillRect(clientRect, QColor(Qt.red))
     painter.drawStaticText(QPoint(10, 10), self.text)
コード例 #16
0
ファイル: bLUeImage.py プロジェクト: valleyzine/bLUe_PYSIDE2
    def histogram(self, size=QSize(200, 200), bgColor=Qt.white, range=(0, 255),
                  chans=channelValues.RGB, chanColors=Qt.gray, mode='RGB', addMode='', clipping_threshold=0.02):
        """
        Plot the image histogram with the
        specified color mode and channels.
        Histograms are smoothed using a Savisky-Golay filter and curves are scaled individually
        to fit the height of the plot.
        @param size: size of the histogram plot
        @type size: int or QSize
        @param bgColor: background color
        @type bgColor: QColor
        @param range: plotted data range
        @type range: 2-uple of int or float
        @param chans: channels to plot B=0, G=1, R=2
        @type chans: list of indices
        @param chanColors: color or 3-uple of colors
        @type chanColors: QColor or 3-uple of QColor
        @param mode: color mode ((one among 'RGB', 'HSpB', 'Lab', 'Luminosity')
        @type mode: str
        @param addMode:
        @type addMode:
        @param clipping_threshold: alert threshold for clipped areas
        @type clipping_threshold: float
        @return: histogram plot
        @rtype: QImage
        """
        binCount = 85  # 255 = 85 * 3
        # convert size to QSize
        if type(size) is int:
            size = QSize(size, size)
        # scaling factor for bin drawing
        spread = float(range[1] - range[0])
        scale = size.width() / spread
        # the last bin is drawn as a vertical line (width = 0),
        # so we correct the scale factor accordingly
        scale *= binCount / (binCount - 1)

        # per channel histogram function
        def drawChannelHistogram(painter, hist, bin_edges, color):
            # Draw histogram for a single channel.
            # param painter: QPainter
            # param hist: histogram to draw
            # smooth the histogram (first and last bins excepted) for a better visualization of clipping.
            # hist = np.concatenate(([hist[0]], SavitzkyGolayFilter.filter(hist[1:-1]), [hist[-1]]))
            # To emphasize significant values we clip the first bin to max height of the others
            M = max(hist[1: ])  # max(hist)  # max(hist[1:-1])
            imgH = size.height()
            # drawing  trapezia instead of rectangles to quickly "smooth" the histogram
            # the rightmost trapezium is not drawn
            poly = QPolygonF()
            poly.append(QPointF(range[0], imgH))  # bottom left point
            for i, y in enumerate(hist):
                try:
                    h = imgH * y / M
                    if np.isnan(h):
                        raise ValueError
                except (ValueError, ArithmeticError, FloatingPointError, ZeroDivisionError):
                    # don't draw the histogram for this channel if M is too small
                    return
                poly.append(QPointF((bin_edges[i] - range[0]) * scale, max(imgH - h, 0)))
                # clipping indicators
                if i == 0 or i == len(hist)-1:
                    left = bin_edges[0 if i == 0 else -1] * scale
                    left = left - (20 if i > 0 else 0)  # shift the indicator at right
                    percent = hist[i] * (bin_edges[i+1]-bin_edges[i])
                    if percent > clipping_threshold:
                        # set the color of the indicator according to percent value
                        nonlocal gPercent
                        gPercent = min(gPercent, np.clip((0.05 - percent) / 0.03, 0, 1))
                        painter.fillRect(left, 0, 10, 10, QColor(255, 255*gPercent, 0))
            # draw the filled polygon
            poly.append(QPointF(poly.constLast().x(), imgH))  # bottom right point
            path = QPainterPath()
            path.addPolygon(poly)
            path.closeSubpath()
            painter.setPen(Qt.NoPen)
            painter.fillPath(path, QBrush(color))
        # end of drawChannelHistogram

        # green percent for clipping indicators
        gPercent = 1.0
        buf = None
        if mode == 'RGB':
            buf = QImageBuffer(self)[:, :, :3][:, :, ::-1]  # RGB
        elif mode == 'HSV':
            buf = self.getHSVBuffer()
        elif mode == 'HSpB':
            buf = self.getHspbBuffer()
        elif mode == 'Lab':
            buf = self.getLabBuffer()
        elif mode == 'Luminosity':
            chans = []
        # drawing the histogram onto img
        img = QImage(size.width(), size.height(), QImage.Format_ARGB32)
        img.fill(bgColor)
        qp = QPainter(img)
        if type(chanColors) is QColor or type(chanColors) is Qt.GlobalColor:
            chanColors = [chanColors]*3
        # compute histograms
        # bins='auto' sometimes causes a huge number of bins ( >= 10**9) and memory error
        # even for small data size (<=250000), so we don't use it.
        if mode == 'Luminosity' or addMode == 'Luminosity':
            bufL = cv2.cvtColor(QImageBuffer(self)[:, :, :3], cv2.COLOR_BGR2GRAY)[..., np.newaxis]  # returns Y (YCrCb) : Y = 0.299*R + 0.587*G + 0.114*B
            hist, bin_edges = np.histogram(bufL, range=range, bins=binCount, density=True)
            drawChannelHistogram(qp, hist, bin_edges, Qt.gray)
        hist_L, bin_edges_L = [0]*len(chans), [0]*len(chans)
        for i, ch in enumerate(chans):
            buf0 = buf[:, :, ch]
            hist_L[i], bin_edges_L[i] = np.histogram(buf0, range=range, bins=binCount, density=True)
            drawChannelHistogram(qp, hist_L[i], bin_edges_L[i], chanColors[ch])
            # subsequent images are added using composition mode Plus
            # qp.setCompositionMode(QPainter.CompositionMode_Plus)  # uncomment for semi-transparent hists
        qp.end()
        """
        buf = QImageBuffer(img)
        # if len(chans) > 1, clip gray area to improve the aspect of the histogram
        if len(chans) > 1:
            buf[:, :, :3] = np.where(np.min(buf, axis=-1)[:, :, np.newaxis] >= 100,
                                     np.array((100, 100, 100))[np.newaxis, np.newaxis, :], buf[:, :, :3])
        """
        return img
コード例 #17
0
ファイル: ImageList.py プロジェクト: robert-clayton/ILYA
 def paintEvent(self, event):
     painter = QPainter(self.viewport())
     painter.setBrush(self.brush)
     painter.setPen(Qt.NoPen)
     painter.drawRect(event.rect())
     super().paintEvent(event)
コード例 #18
0
############
# launch app
############
QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)  # needed when a plugin initializes a Qt WebEngine
app = QApplication(sys.argv)
# get root widget
rootWidget = app.desktop()

#################
# init main form
# the UI is not loaded yet
window = Form1()
#################

# init global QPainter for paint event
qp = QPainter()
# stuff for Before/After tags
qp.font = QFont("Arial", 8)
qp.markPath = QPainterPath()
qp.markRect = QRect(0, 0, 50, 20)
qp.markPath.addRoundedRect(qp.markRect, 5, 5)


def paintEvent(widg, e, qp=qp):
    """
    Paint event handler.
    It displays the presentation layer of a vImage object in a Qlabel,
    with current offset and zooming coefficient.
    The widget must have a valid img attribute of type vImage.
    The handler should be used to override the paintEvent method of widg. This can be done
    by subclassing (not directly compatible with Qt Designer) or by assigning paintEvent
コード例 #19
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.HighQualityAntialiasing)

        # determine max width/height of all labels
        if self._maxLabelWidth is None or self._maxLabelHeight is None:
            self._maxLabelWidth = 0
            self._maxLabelHeight = 0
            for k in self.labels.values():
                b = painter.boundingRect(
                    QRectF(0, 0, 0, 0),
                    int(Qt.AlignLeft) | int(Qt.AlignVCenter), str(k))
                self._maxLabelWidth = max(self._maxLabelWidth, b.width())
                self._maxLabelHeight = max(self._maxLabelHeight, b.height())

        barRect = self.rect()

        if self._orientation == 'Vertical':
            # translate Y axis
            matrix = QMatrix()
            matrix.translate(0, self.height() - self.margin)
            matrix.scale(1, -1)
            painter.setMatrix(matrix)

            self.gradient.setFinalStop(0, self.height() - self.margin)
            barRect.setWidth(self._barThickness)
            barRect.setHeight(barRect.height() - 2 * self.margin)
            painter.fillRect(barRect, self.gradient)

            # restore normal coordinates
            painter.scale(1, -1)

            self.setMinimumWidth(self._barThickness + self._labelMargin +
                                 self._maxLabelWidth)

        elif self._orientation == 'Horizontal':
            self.margin = self._maxLabelWidth / 2 + self._labelMargin
            barRect.setHeight(self._barThickness)
            barRect.setLeft(
                self.margin
            )  # reduces width by margin (as opposed to shifting)

            # Reduce the width by another margin to pull off the right hand side
            barRect.setWidth(barRect.width() - self.margin)

            painter.fillRect(barRect, self.gradient)

            line_step = barRect.width() / 20
            pos = barRect.left()
            while pos <= barRect.right():
                painter.drawLine(pos,
                                 2 * (barRect.bottom() - barRect.top()) / 3,
                                 pos, barRect.bottom())
                pos += line_step

            self.setMinimumHeight(self._maxLabelHeight + self._barThickness +
                                  self._labelMargin)

        for pos, label in self.labels.items():
            # Figure coordinate position. 1=height-margin for vertical, or width-margin for horizontal
            if self._orientation == 'Vertical':
                lpos = -1 * ((self.height() - (2 * self.margin)) * pos)
                painter.drawText(self._barThickness + self._labelMargin,
                                 (.5 * self._maxLabelHeight) + lpos, label)
            elif self._orientation == 'Horizontal':
                text_rect = painter.boundingRect(QRectF(0, 0, 0, 0),
                                                 int(Qt.AlignLeft), str(label))
                lpos = ((self.width() - (2 * self.margin)) * pos
                        )  # Center position
                lleft = lpos - text_rect.width() / 2
                painter.drawText(lleft + self.margin, self.height() - 1, label)
コード例 #20
0
 def paintEvent(self, event):
     """ Paint the editor, offloading the work to the StarRating class. """
     painter = QPainter(self)
     self.starRating.paint(painter, self.rect(), self.palette(), isEditable=True)
コード例 #21
0
ファイル: qpicture_test.py プロジェクト: hz658832/PySide2
 def paintEvent(self, e):
     p = QPainter(self)
     p.drawPicture(0, 0, self._picture)
     self._app.quit()
コード例 #22
0
    def paintEvent(self, event: QPaintEvent):
        """
        The place where the drawing takes palce.
        
        ...
        Parameters
        --------------
        none.

        Return
        --------------
        none.
        """

        if self.spb_dynamicMin:
            self.setMinimumSize(
                QSize(self.lineWidth * 6 + self.pathWidth * 6,
                      self.lineWidth * 6 + self.pathWidth * 6))

        spiralProgressBar.spb_MinimumSize(self, self.spb_dynamicMax,
                                          self.spb_minimSize,
                                          self.spb_maximSize)
        spiralProgressBar.geometricFactor(self)
        spiralIncrem = 0
        spiralIncrem2 = 0

        if self.pathIndepend != True:
            self.pathWidth = self.lineWidth
        self.tempWidth = self.pathWidth
        if self.pathPresent:
            for path in range(0, self.noProgBar, 1):
                if self.varWidth == True:  #CREAETS A INCREASING OR DECREASING TYPE OF WITH
                    self.tempWidth = self.tempWidth + self.widthIncr
                    if self.gapCngd != True:
                        self.spb_gap = self.tempWidth * 2
                self.pathPainter = QPainter(self)
                self.pathPainter.setRenderHint(QPainter.Antialiasing)
                self.penPath = QPen()
                self.penPath.setStyle(self.pathStyle[path])
                self.penPath.setWidth(self.tempWidth)
                self.penPath.setBrush(
                    QColor(self.pathColor[path][0], self.pathColor[path][1],
                           self.pathColor[path][2]))
                self.pathPainter.setPen(self.penPath)
                self.pathPainter.drawArc(
                    self.positionX + self.posFactor +
                    self.spb_cngSize * spiralIncrem2, self.positionY +
                    self.posFactor + self.spb_cngSize * spiralIncrem2,
                    self.spb_Size - self.sizeFactor -
                    2 * self.spb_cngSize * spiralIncrem2, self.spb_Size -
                    self.sizeFactor - 2 * self.spb_cngSize * spiralIncrem2,
                    self.spb_startPos[path], 360 * 16)
                self.pathPainter.end()
                spiralIncrem2 = spiralIncrem2 + self.spb_gap

        self.tempWidth = self.lineWidth  #TEMPWIDTH TEMPORARLY STORES THE LINEWIDTH, USEFUL IN VARIABLE WIDTH OPTION.
        for bar in range(0, self.noProgBar, 1):
            if self.varWidth == True:  #CREAETS A INCREASING OR DECREASING TYPE OF WITH
                self.tempWidth = self.tempWidth + self.widthIncr
                if self.gapCngd != True:
                    self.spb_gap = self.tempWidth * 2
            self.linePainter = QPainter(self)
            self.linePainter.setRenderHint(QPainter.Antialiasing)
            self.penLine = QPen()
            self.penLine.setStyle(self.lineStyle[bar])
            self.penLine.setWidth(self.tempWidth)
            self.penLine.setCapStyle(self.lineCap[bar])
            self.penLine.setBrush(
                QColor(self.lineColor[bar][0], self.lineColor[bar][1],
                       self.lineColor[bar][2]))
            self.linePainter.setPen(self.penLine)
            self.linePainter.drawArc(
                self.positionX + self.posFactor +
                self.spb_cngSize * spiralIncrem, self.positionY +
                self.posFactor + self.spb_cngSize * spiralIncrem,
                self.spb_Size - self.sizeFactor -
                2 * self.spb_cngSize * spiralIncrem, self.spb_Size -
                self.sizeFactor - 2 * self.spb_cngSize * spiralIncrem,
                self.spb_startPos[bar], self.spb_value[bar])
            self.linePainter.end()
            spiralIncrem = spiralIncrem + self.spb_gap
コード例 #23
0
def _test_pipedimagerpq():
    # vertices of a pentagon (roughly) centered in a 1000 x 1000 square
    pentagonpts = (
        (504.5, 100.0),
        (100.0, 393.9),
        (254.5, 869.4),
        (754.5, 869.4),
        (909.0, 393.9),
    )
    linepts = ((350, 50), (200, 150), (400, 250), (300, 350), (150, 250),
               (100, 450))
    # start PyQt
    testapp = QApplication(["PipedImagerPQ"])
    # create the list of commands to submit
    drawcmnds = []
    drawcmnds.append({"action": "setTitle", "title": "Tester"})
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "clear", "color": "black"})
    drawcmnds.append({"action": "screenInfo"})
    # create the image to be displayed
    testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied)
    # initialize a black background
    testimage.fill(0xFF000000)
    # draw some things in the image
    testpainter = QPainter(testimage)
    testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0,
             Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin))
    testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0))
    testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine,
             Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolygon(
        QPolygonF([
            QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts
        ]))
    testpainter.setBrush(Qt.NoBrush)
    testpainter.setPen(
        QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0,
             Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolyline(
        QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts]))
    testpainter.end()
    # add the image command
    testimgwidth = testimage.width()
    testimgheight = testimage.height()
    testimgstride = testimage.bytesPerLine()
    # not a good way to get the pixel data
    testimgdata = bytearray(testimgheight * testimgstride)
    k = 0
    for pty in range(testimgheight):
        for ptx in range(testimgwidth):
            pixval = testimage.pixel(ptx, pty)
            (aval, rgbval) = divmod(pixval, 256 * 256 * 256)
            (rval, gbval) = divmod(rgbval, 256 * 256)
            (gval, bval) = divmod(gbval, 256)
            testimgdata[k] = bval
            k += 1
            testimgdata[k] = gval
            k += 1
            testimgdata[k] = rval
            k += 1
            testimgdata[k] = aval
            k += 1
    testblocksize = 4000
    testnumblocks = (testimgheight * testimgstride + testblocksize -
                     1) // testblocksize
    drawcmnds.append({
        "action": "newImage",
        "width": testimgwidth,
        "height": testimgheight,
        "stride": testimgstride
    })
    for k in range(testnumblocks):
        if k < (testnumblocks - 1):
            blkdata = testimgdata[k * testblocksize:(k + 1) * testblocksize]
        else:
            blkdata = testimgdata[k * testblocksize:]
        drawcmnds.append({
            "action": "newImage",
            "blocknum": k + 1,
            "numblocks": testnumblocks,
            "startindex": k * testblocksize,
            "blockdata": blkdata
        })
    # finish the command list
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "exit"})
    # create a PipedImagerPQ in this process
    (cmndrecvpipe, cmndsendpipe) = multiprocessing.Pipe(False)
    (rspdrecvpipe, rspdsendpipe) = multiprocessing.Pipe(False)
    testviewer = PipedImagerPQ(cmndrecvpipe, rspdsendpipe)
    # create a command submitter dialog
    tester = _CommandSubmitterPQ(testviewer, cmndsendpipe, rspdrecvpipe,
                                 drawcmnds)
    tester.show()
    # let it all run
    testresult = testapp.exec_()
    if testresult != 0:
        sys.exit(testresult)
コード例 #24
0
ファイル: Map.py プロジェクト: mugenZebra/SLAM_Qt
 def addVehicle(self):
     self.image = self.image.convertToFormat(QImage.Format_RGBA8888)
     painter = QPainter(self.image)
     painter.drawImage(QRect(50, 50, 13, 15), QImage("imgs/turtle.png"))
     painter.end()
     self.update()
コード例 #25
0
 def paintEvent(self, event: QPaintEvent) -> None:
     painter: QPainter = QPainter(self)
     painter.fillRect(self.rect(), self.__bgColor)
コード例 #26
0
 def paintEvent(self, event):
     painter = QPainter(self)
     self.line_graph.paint(painter)
コード例 #27
0
ファイル: tile.py プロジェクト: shieldforever/checkers-game
 def paintEvent(self, pe):
     o = QStyleOption()
     o.initFrom(self)
     p = QPainter(self)
     self.style().drawPrimitive(QStyle.PE_Widget, o, p, self)
コード例 #28
0
 def render(self):
     clientRect = QRect(QPoint(0, 0), self.size())
     painter = QPainter(self.backingStore.paintDevice())
     painter.fillRect(clientRect, QColor(Qt.green))
     painter.drawStaticText(QPoint(10, 10), self.text)
コード例 #29
0
ファイル: MP4EventHandler.py プロジェクト: kaisaryousuf/pyrdp
 def notifyImage(self, x: int, y: int, img: QImage, width: int,
                 height: int):
     p = QPainter(self.buffer)
     p.drawImage(x, y, img, 0, 0, width, height)
コード例 #30
0
def draw_circle(radius, x, y, border_color, fill_color, widget):
    painter = QPainter(widget)
    painter.setRenderHint(QPainter.Antialiasing, True)
    painter.setPen(QPen(border_color, 1.5, Qt.SolidLine))
    painter.setBrush(QBrush(fill_color))
    painter.drawEllipse(x - radius, y - radius, radius * 2, radius * 2)