Exemple #1
0
    def set_debugging_status(self, status):
        if status == 0:
            text = "Idle ..."
            color = "gray"
        elif status == 1:
            text = 'Waiting for connection ...'
            color = "orange"
        elif status == 2:
            text = 'Debugging stopped ...'
            color = "red"
        elif status == 3:
            text = 'Debugging in progress ...'
            color = "green"
        elif status == 4:
            text = 'Running ...'
            color = "blue"

        self.label.setText(text)

        self.pixmap = QPixmap(10, 10)
        color = QColor(color)
        self.pixmap.fill(color)
        painter = QPainter(self.pixmap)
        painter.drawRect(0, 0, 10, 10)
        self.light.setPixmap(self.pixmap)
 def paintEvent(self, QPaintEvent):
     qp = QPainter()
     image = QImage("default.png")
     image = image.scaled(32, 32)
     sky_image = QImage("sky.png")
     qp.begin(self)
     qp.drawImage(0, 0, sky_image)
     for obj in game_manager.GameManager.get_all_objects():
         pos = obj.get_position()
         size = obj.get_size()
         #if isinstance(obj, object.MovingObject):
             #qp.setPen(QColor(0, 0, 0))
         #else:
             #qp.setPen(QColor(255, 0, 0))
         if obj is object.Bullet:
             pass
         if isinstance(obj, object.Unit):
             qp.drawImage(pos.x + START_PLAYER_POSITION[0] - game_manager.GameManager.player.get_position().x,
                      pos.y + START_PLAYER_POSITION[1] - game_manager.GameManager.player.get_position().y,
                      image)
         else:
             qp.drawRect(pos.x + START_PLAYER_POSITION[0] - game_manager.GameManager.player.get_position().x,
             pos.y + START_PLAYER_POSITION[1] - game_manager.GameManager.player.get_position().y,
             size.x, size.y)
     #qp.setPen(QColor(255, 0, 0))
     #for x in game_manager.GameManager.get_map().grid.keys():
         #for y in game_manager.GameManager.get_map().grid[x].keys():
             #qp.drawRect(x + START_PLAYER_POSITION[0] - game_manager.GameManager.player.get_position().x,
                         #y + START_PLAYER_POSITION[1] - game_manager.GameManager.player.get_position().y,
                         #TILE_LENGHT, TILE_LENGHT)
     qp.end()
Exemple #3
0
    def paintEvent(self, event):
        logger.debug("paintEvent: {0} - {1}".format(self, event.rect()))
        qp = QPainter()
        qp.begin(self)
        
        width = self.size().width() - 1 
        height = self.size().height() - 1 

        #draw border
        qp.setPen(self.border_color)
        qp.drawRect(0,0, width, height)
        
        #draw plot
        width  -= 1
        height -= 1
        if len(self.data):
            max_val = max(map(lambda x: x[-1], self.data))
            plots = [list() for _ in range(self.num_data_points) ]
            for index in range(len(self.data)-1, 1, -1):
                for inner_index in range(self.num_data_points):
                    plots[inner_index].append(QPoint((width / self.data.maxlen * index),
                                                     height - (height / max_val * self.data[index][inner_index])))
            for x in range(len(plots)-1, -1, -1):
                qp.setPen(self.plot_colors[x])
                qp.setBrush(self.plot_colors[x])
                points = plots[x]
                points.append(QPoint(1,     height))
                points.append(QPoint(width, height))
                qp.drawPolygon(*points)
        qp.end()
        logger.debug("paintEvent End: {0}".format(self))
Exemple #4
0
    def paintEvent(self, ev):
        color = self.palette().color(QPalette.Highlight)
        painter = QPainter(self)

        # Filled rectangle.
        painter.setClipRect(self.rect())
        color.setAlpha(50)
        painter.fillRect(self.rect().adjusted(2,2,-2,-2), color)

        # Thin rectangle outside.
        color.setAlpha(150)
        painter.setPen(color)
        painter.drawRect(self.rect().adjusted(0,0,-1,-1))

        # Pseudo-handles at the corners and sides
        color.setAlpha(100)
        pen = QPen(color)
        pen.setWidth(8)
        painter.setPen(pen)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Clip at 4 corners
        region = QRegion(QRect(0,0,20,20))
        region += QRect(self.rect().width()-20, 0, 20, 20)
        region += QRect(self.rect().width()-20, self.rect().height()-20, 20, 20)
        region += QRect(0, self.rect().height()-20, 20, 20)
        # Clip middles
        region += QRect(0, self.rect().height() // 2 - 10, self.rect().width(), 20)
        region += QRect(self.rect().width() // 2 - 10, 0, 20, self.rect().height())
        
        # Draw thicker rectangles, clipped at corners and sides.
        painter.setClipRegion(region)
        painter.drawRect(self.rect())
    def __redrawColorLabel(self, label, lc, uc):
        pixmap = QPixmap(101, 26)
        painter = QPainter(pixmap)
        lowerColorRect = QRect(0, 0, 50, 25)
        upperColorRect = QRect(50, 0, 50, 25)

        font = QFont("Times", 11)
        painter.setFont(font)

        painter.setPen(Qt.black)
        painter.setBrush(lc)
        painter.drawRect(lowerColorRect)
        lgray = lc.red() + lc.green() + lc.blue()
        painter.setPen(self.invert(lc))
        painter.drawText(lowerColorRect.translated(8, 2), 0, str(lgray))

        painter.setPen(Qt.black)
        painter.setBrush(uc)
        painter.drawRect(upperColorRect)
        ugray = uc.red() + uc.green() + uc.blue()
        painter.setPen(self.invert(uc))
        painter.drawText(upperColorRect.translated(8, 2), 0, str(ugray))
        del painter

        label.setPixmap(pixmap)
	def drawROIBoxes(self, image):
		#print(self.frame_data)
		if not isinstance(self.frame_data, pd.DataFrame) or len(self.frame_data) == 0 \
		or not self.label_type in self.frame_data:
			return 
		 			
		self.img_h_ratio = image.height()/self.image_height;
		self.img_w_ratio = image.width()/self.image_width;

		painter = QPainter()
		painter.begin(image)
		for row_id, row_data in self.frame_data.iterrows():
			x = row_data['coord_x']*self.img_h_ratio
			y = row_data['coord_y']*self.img_w_ratio
			#check if the coordinates are nan
			if not (x == x) or  not (y == y): 
				continue

			x = int(x)
			y = int(y)
			c = self.wlabC[int(row_data[self.label_type])]
			
			painter.setPen(c)
			painter.setFont(QFont('Decorative', 10))
			
			painter.drawText(x, y, str(int(row_data[self.worm_index_type])))

			bb = row_data['roi_size']*self.img_w_ratio
			painter.drawRect(x-bb/2, y-bb/2, bb, bb);
		painter.end()
Exemple #7
0
    def paintQR(self, data):
        if not data:
            return
        qr = qrcode.QRCode()
        qr.add_data(data)
        matrix = qr.get_matrix()
        k = len(matrix)
        border_color = Qt.white
        base_img = QImage(k * 5, k * 5, QImage.Format_ARGB32)
        base_img.fill(border_color)
        qrpainter = QPainter()
        qrpainter.begin(base_img)
        boxsize = 5
        size = k * boxsize
        left = (base_img.width() - size)/2
        top = (base_img.height() - size)/2
        qrpainter.setBrush(Qt.black)
        qrpainter.setPen(Qt.black)

        for r in range(k):
            for c in range(k):
                if matrix[r][c]:
                    qrpainter.drawRect(left+c*boxsize, top+r*boxsize, boxsize - 1, boxsize - 1)
        qrpainter.end()
        return base_img
Exemple #8
0
    def buildCharPreview(self):        
        char = self.selectedChar - self.charFrom.value()
        if char < 0:
            char = 0
        if char >= len(self.charSizes):
            char = len(self.charSizes) - 1
        
        k = 5
        s_x = self.charSizes[char][0]
        w = self.charSizes[char][1]
        
        charPix = self.chars.pixmap()
        charImage = charPix.toImage()

        self.charPreview.resize(w * k + 1, charPix.height() * k + 1)

        pix = QPixmap(w * k, charPix.height() * k)
        p = QPainter()
        p.begin(pix)
        p.setBrush(QBrush(QColor(0xffffff), Qt.SolidPattern))
        p.drawRect(0, 0, pix.width() - 1, pix.height() - 1)

        p.setBrush(QBrush(QColor(0x0), Qt.SolidPattern))        
        for x in range(w):
            for y in range(charPix.height()):
                if QColor(charImage.pixel(s_x + x, y)).lightness() == 0x0:
                    p.drawRect(x * k, y * k, k, k)
        p.end()
        self.charPreview.setPixmap(pix)
Exemple #9
0
    def paintEvent(self, event):
        logger.debug("paintEvent: {0} - {1}".format(self, event.rect()))
        qp = QPainter()
        qp.begin(self)
        
        width = self.size().width() - 1 
        height = self.size().height() - 1 

        #draw border
        qp.setPen(self.border_color)
        qp.drawLine(0, 0, width, 0)
        qp.drawLine(0, 0, 0, height)
        qp.drawLine(width, 0, width, height)
        qp.drawLine(0, height, width, height)

        #draw bar
        width  -= 2
        height -= 2
        value = orig_value = self.data_source()
        value = min(self.max_range, value)
        value = max(self.min_range, value)
        qp.setPen(self.bar_color)
        qp.setBrush(self.bar_color)
        if self.orientation == 'horizontal':
            qp.drawRect(1, 1,
                        width / self.max_range * value, height)
        else:
            qp.drawRect(1, height - (height / self.max_range * value), width, height)
        qp.setPen(self.border_color)
        qp.drawText(event.rect(), Qt.AlignCenter, str(orig_value))
        qp.end()
        logger.debug("paintEvent End: {0}".format(self))
Exemple #10
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                            "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Exemple #11
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     painter = QPainter(self)
     painter.setBrush(QBrush(QColor(Qt.black)))
     painter.setPen(QPen())
     painter.setOpacity(self.value)
     painter.drawRect(self.rect())
Exemple #12
0
    def render(self, painter: QPainter) -> None:
        if self._item_style == FileItemStyle.SMALLICON:
            self.paint_smallicon_view(painter)
        elif self._item_style == FileItemStyle.DETAIL:
            self.paint_detail_view(painter)
        else:
            self.paint(painter)

        if self.is_selected:
            painter.save()
            painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
            painter.setOpacity(0.5)
            painter.fillRect(self.tile_rect, QColor(127, 192, 255))
            painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
            painter.setOpacity(1.0)
            painter.setPen(QColor(96, 127, 255))
            painter.setBrush(Qt.NoBrush)
            painter.drawRect(self.tile_rect)
            painter.restore()

        if self.is_cursor:
            painter.setOpacity(1.0)
            painter.setPen(QColor(0, 0, 0))
            painter.setBrush(QColor(255, 255, 255, 96))
            painter.drawRect(self.tile_rect)
Exemple #13
0
def createThemePreview(theme, screenRect, size=QSize(200, 120)):
    if type(theme) == str and os.path.exists(theme):
        # Theme is the path to an ini file
        themeDatas = loadThemeDatas(theme)
    else:
        themeDatas = theme

    pixmap = generateTheme(themeDatas, screenRect)

    addThemePreviewText(pixmap, themeDatas, screenRect)

    px = QPixmap(pixmap).scaled(size, Qt.KeepAspectRatio)

    w = px.width() / 10
    h = px.height() / 10
    r = themeTextRect(themeDatas, screenRect)

    painter = QPainter(px)
    painter.drawPixmap(QRect(w, h, w * 4, h * 5), pixmap,
                       QRect(r.topLeft() - QPoint(w / 3, h / 3), QSize(w * 4, h * 5)))
    painter.setPen(Qt.white)
    painter.drawRect(QRect(w, h, w * 4, h * 5))
    painter.end()

    return px
Exemple #14
0
	def paintEvent(self, paintEvent):
		painter = QPainter(self)
		painter.setClipRect(paintEvent.rect())

		color = self.__editor.palette().text()
		painter.setPen(QPen(color, self.__lineWidth))
		painter.drawRect(self.rect())
Exemple #15
0
 def drawPixmapFor3d(self):
     self.pixmap3d = QPixmap(self.itemWidth, self.itemHeight)
     self.pixmap3d.fill(Qt.transparent)
     painter = QPainter()
     painter.begin(self.pixmap3d)
     painter.setRenderHint(QPainter.Antialiasing)
     pen = QPen()
     pen.setWidth(2)
     painter.setPen(pen)
     painter.setBrush(QBrush(QColor(220, 220, 220)))
     top = [QPoint(5, 10),
            QPoint(self.itemWidth - 10, 10),
            QPoint(self.itemWidth - 5, 5),
            QPoint(10, 5),
            QPoint(5, 10)]
     painter.drawConvexPolygon(*top)
     left = [QPoint(self.itemWidth - 10, 10),
             QPoint(self.itemWidth - 10, self.itemHeight - 5),
             QPoint(self.itemWidth - 5, self.itemHeight - 10),
             QPoint(self.itemWidth - 5, 5),
             QPoint(self.itemWidth - 10, 10)]
     painter.drawConvexPolygon(*left)
     painter.setBrush(QBrush())
     painter.drawRect(QRect(5, 10, self.itemWidth - 15, self.itemHeight - 15))
     painter.drawText(QRect(5, 10, self.itemWidth - 15, self.itemHeight - 15), Qt.AlignCenter, '3D')
     painter.end()
Exemple #16
0
 def __drawPasteRect(self, pos):
     """
     Private slot to draw a rectangle for signaling a paste operation.
     
     @param pos widget position of the paste rectangle (QPoint)
     """
     self.__markImage.fill(self.NoMarkColor.rgba())
     if self.__pasteRect.isValid():
         self.__updateImageRect(
             self.__pasteRect.topLeft(),
             self.__pasteRect.bottomRight() + QPoint(1, 1))
     
     x, y = self.__imageCoordinates(pos)
     isize = self.__image.size()
     if x + self.__clipboardSize.width() <= isize.width():
         sx = self.__clipboardSize.width()
     else:
         sx = isize.width() - x
     if y + self.__clipboardSize.height() <= isize.height():
         sy = self.__clipboardSize.height()
     else:
         sy = isize.height() - y
     
     self.__pasteRect = QRect(QPoint(x, y), QSize(sx - 1, sy - 1))
     
     painter = QPainter(self.__markImage)
     painter.setPen(self.MarkColor)
     painter.drawRect(self.__pasteRect)
     painter.end()
     
     self.__updateImageRect(self.__pasteRect.topLeft(),
                            self.__pasteRect.bottomRight() + QPoint(1, 1))
    def _redrawColorLabel(self, labelIndex, lc, uc, lValue, uValue) :
        if labelIndex >= len(self.__colorLabels) :
            return
        label = self.__colorLabels[labelIndex]
        pixmap = QPixmap(101, 26)
        painter = QPainter(pixmap)
        lowerColorRect = QRect(0, 0, 50, 25)
        upperColorRect = QRect(50, 0, 50, 25)

        font = QFont('Times', 11)
        painter.setFont(font)

        painter.setPen(Qt.black);
        painter.setBrush(lc);
        painter.drawRect(lowerColorRect);
        painter.setPen(self.invert(lc));
        painter.drawText(lowerColorRect.translated(8, 2), 0, str(lValue));

        painter.setPen(Qt.black);
        painter.setBrush(uc);
        painter.drawRect(upperColorRect);
        painter.setPen(self.invert(uc));
        painter.drawText(upperColorRect.translated(8, 2), 0, str(uValue));
        del painter

        label.setPixmap(pixmap);
    def paintEvent(self, event):
        painter = QPainter(self)
        if self.pixmap:
            size = self.pixmap.size()
            aspect = float(size.width()) / size.height()
            if aspect > 1:
                # Image is wider than it is tall - centre vertically
                left = 0
                width = self.width()
                height = self.height() / aspect
                top = (self.height() - height) / 2
            else:
                # Image is taller than it is wide - centre horizontally
                top = 0
                height = self.height()
                width = self.width() * aspect
                left = (self.width() - width) / 2

            painter.drawPixmap(QRect(left, top, width, height), self.pixmap)

            if self.focus:
                # self.focus contains coords between 0 and 1 - translate these
                # to pixels
                pixels = QRectF(left + self.focus.left() * width,
                                top + self.focus.top() * height,
                                self.focus.width() * width,
                                self.focus.height() * height)
                # Outer box in white
                painter.setPen(QPen(Qt.white, 1, Qt.SolidLine))
                painter.drawRect(pixels)
                # Inner box in black
                painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                painter.drawRect(pixels.adjusted(1, 1, -1, -1))
Exemple #19
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setPen (QPen(QColor(0,0,0,0)))
        ysize, xsize = self.layout.shape
        canvas = self.contentsRect()
        for y in range(ysize):
            for x in range(xsize):
                qp.setBrush(self.colors[self.layout.grid[y][x]])
                qp.drawRect(TILE_SIZE * x, TILE_SIZE * y, TILE_SIZE, TILE_SIZE)
                #Color(rgb=self.colors[self.layout.grid[y][x]])
                #Rectangle(pos=(TILE_SIZE * x, TILE_SIZE * y), size=(TILE_SIZE, TILE_SIZE))

        pac_x = self.current_game_state.agents[0].position[0] * TILE_SIZE
        pac_y = self.current_game_state.agents[0].position[1] * TILE_SIZE
        qp.setBrush(QBrush(QColor(255,255,0)))
        qp.drawEllipse(pac_x, pac_y, TILE_SIZE, TILE_SIZE)

        for g in self.current_game_state.agents[1:]:
            g_x = g.position[0] * TILE_SIZE
            g_y = g.position[1] * TILE_SIZE
            qp.setBrush(QBrush(QColor(255,0,0)))
            qp.drawEllipse(g_x, g_y, TILE_SIZE, TILE_SIZE)

        for y in range(ysize):
            for x in range(xsize):
                if self.current_game_state.food[y][x]:
                    qp.setBrush(QBrush(QColor(255,255,255)))
                    qp.drawEllipse(x * TILE_SIZE + TILE_SIZE / 2,
                                 y * TILE_SIZE + TILE_SIZE / 2,
                            TILE_SIZE / 4, TILE_SIZE / 4)

        qp.end()
Exemple #20
0
	def paintEvent(self,event):
		super().paintEvent(event)
		painter = QPainter(self)
		painter.fillRect(4,4,frameWidth,frameHeight,self.backBrush)
		painter.drawPixmap(4+(frameWidth-self.pixMap.width())//2,4+(frameHeight-self.pixMap.height())//2,self.pixMap)
		if self.isChecked():
			painter.setPen(self.checkedPen)
			painter.drawRect(3,3,self.width()-6,self.height()-6)
 def paintEvent(self, _event):
     qp = QPainter(self)
     qp.setBrush(QBrush(self.color))
     qp.setPen(self.color)
     qp.drawRect(0, 0, 25, 25)
     qp.setBrush(Qt.NoBrush)
     qp.setPen(Qt.black)
     qp.drawRect(1, 1, 24, 24)
Exemple #22
0
    def createRoundButtonBackground(self, transform):
        scaledRect = transform.mapRect(QRect(0, 0,
                self.logicalSize.width(), self.logicalSize.height()))

        image = QImage(scaledRect.width(), scaledRect.height(),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setPen(QColor(120, 120, 120))
            if self.pressed:
                painter.setBrush(QColor(60, 60, 60))
            elif self.highlighted:
                painter.setBrush(QColor(100, 100, 100))
            else:
                painter.setBrush(QColor(80, 80, 80))
        else:
            outlinebrush = QLinearGradient(0, 0, 0, scaledRect.height())
            brush = QLinearGradient(0, 0, 0, scaledRect.height())

            brush.setSpread(QLinearGradient.PadSpread)
            highlight = QColor(255, 255, 255, 70)
            shadow = QColor(0, 0, 0, 70)
            sunken = QColor(220, 220, 220, 30)

            if self.type == TextButton.PANEL:
                normal1 = QColor(200, 170, 160, 50)
                normal2 = QColor(50, 10, 0, 50)
            else:
                normal1 = QColor(255, 255, 245, 60)
                normal2 = QColor(255, 255, 235, 10)

            if self.pressed:
                outlinebrush.setColorAt(0, shadow)
                outlinebrush.setColorAt(1, highlight)
                brush.setColorAt(0, sunken)
                painter.setPen(Qt.NoPen)
            else:
                outlinebrush.setColorAt(1, shadow)
                outlinebrush.setColorAt(0, highlight)
                brush.setColorAt(0, normal1)
                if not self.highlighted:
                    brush.setColorAt(1, normal2)
                painter.setPen(QPen(outlinebrush, 1))

            painter.setBrush(brush)

        if self.type == TextButton.PANEL:
            painter.drawRect(0, 0, scaledRect.width(), scaledRect.height())
        else:
            painter.drawRoundedRect(0, 0, scaledRect.width(),
                    scaledRect.height(), 10, 90, Qt.RelativeSize)

        return image
Exemple #23
0
 def paintEvent(self, event):    
     painter = QPainter(self)
     self.font.setPixelSize(self.height() - self.padding * 2)
     painter.setBrush(QtGui.QColor(0, 0, 0, 255))
     painter.drawRect(0, 0, self.width(), self.height())
     painter.setPen(QtGui.QColor(19, 125, 17, 255))
     painter.setFont(self.font)
     painter.drawText(0, 0, self.width(), self.height(), QtCore.Qt.AlignRight, self.info_string)
     painter.end()
Exemple #24
0
    def paintEvent(self, event):
        if self.pendingMessageCount() == 0:
            QWidget.paintEvent(self, event)
            return

        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        painter.setBrush(self.currentMessageBackground())
        painter.drawRect(self.contentsRect())
Exemple #25
0
    def paintEvent(self, event):
        if self._queuedWidget.pendingMessageCount() == 0:
            QToolBar.paintEvent(self, event)
            return

        brush = self._queuedWidget.currentMessageBackground()
        painter = QPainter(self)
        painter.setPen(brush.color().darker(150))
        painter.setBrush(brush)
        painter.drawRect(self.contentsRect().adjusted(0, 0, -1, -1))
Exemple #26
0
 def paintEvent(self, _event):
     qp = QPainter()
     qp.begin(self)
     qp.setBrush(QBrush(self.color))
     qp.setPen(self.color)
     qp.drawRect(0, 0, 15, 15)
     qp.setBrush(Qt.NoBrush)
     qp.setPen(Qt.black)
     qp.drawRect(1, 1, 14, 14)
     qp.end()
Exemple #27
0
 def paintEvent(self, event):    
     if self.qimage:
         painter = QPainter(self)
         painter.drawImage(QtCore.QRect(0, 0, self.width(), self.height()), self.qimage)
         painter.end()
     else:
         painter = QPainter(self)
         painter.setBrush(QtGui.QColor(255, 255, 255, 255))
         painter.drawRect(0, 0, self.width(), self.height())
         painter.end()
Exemple #28
0
	def paintEvent(self,event):
		painter = QPainter(self)
		x = self.lastPoint.x()
		y = self.lastPoint.y()
		w = self.endPoint.x() - x
		h = self.endPoint.y() - y

		pp = QPainter(self.pix)
		pp.drawRect(x, y, w, h)
		painter.drawPixmap(0, 0, self.pix)
 def _drawPlanetPic(self, painter: QPainter):
     if self._img_loaded:
         painter.drawImage(self._img.rect(), self._img, self._img.rect(), Qt.AutoColor)
     if self._planet.is_current:
         pen = QPen(QColor(0, 200, 0))
         pen.setWidth(4)
         painter.setPen(pen)
         rc = self.rect()
         rc.adjust(0, 0, -1, -1)
         painter.drawRect(rc)
Exemple #30
0
    def paint_line_numbers(self, line_numbers, event):
        """Paint the line numbers

        For every visible block in the document draw it's corresponding line
        number in the line numbers widget.
        """
        font_metrics = self.document_contents.fontMetrics()

        painter = QPainter(line_numbers)
        painter.fillRect(event.rect(), self.document_contents.palette().base())

        block = self.document_contents.firstVisibleBlock()
        line_number = block.blockNumber()

        height = font_metrics.height()
        width = line_numbers.width()

        while block.isValid():
            # blocks are numbered from zero
            line_number += 1

            content_offset = self.document_contents.contentOffset()
            # Get the top coordinate of the current block
            # to know where to paint the line number for it
            block_top = (self.document_contents
                             .blockBoundingGeometry(block)
                             .translated(content_offset)
                             .top())

            if not block.isVisible() or block_top >= event.rect().bottom():
                break

            # If block has a breakpoint,
            # draw a green rectangle by the line number
            # if the block number matches the current line number
            # make it red, as it is then a breakpoint hit
            if self.document_contents.block_has_breakpoint(block):
                brush = painter.brush()
                brush.setStyle(Qt.SolidPattern)
                if self.document_contents.block_is_current(block):
                    brush.setColor(Qt.red)
                else:
                    brush.setColor(Qt.darkGreen)
                painter.setBrush(brush)
                rect = QRect(0, block_top+2, 7, 7)
                painter.drawRect(rect)

            # Convert the line number to string so we can paint it
            text = str(line_number)

            painter.drawText(0, block_top, width, height, Qt.AlignRight, text)

            block = block.next()

        painter.end()
Exemple #31
0
    def getBalloonImage(self, size: QSize, flip=False, soul_id=-1):
        if self._balloon is None:
            logging.warning("getBalloonImage: balloon is None")
            return kikka.helper.getDefaultImage()

        drect = []
        # calculate destination rect
        if len(self._balloon.clipW) == 3:
            dw = [
                self._balloon.clipW[0],
                size.width() - self._balloon.clipW[0] - self._balloon.clipW[2],
                self._balloon.clipW[2]
            ]
        elif len(self._balloon.clipW) == 5:
            sw = size.width() - self._balloon.clipW[0] - self._balloon.clipW[
                2] - self._balloon.clipW[4]
            dw = [
                self._balloon.clipW[0], sw // 2, self._balloon.clipW[2],
                sw - sw // 2, self._balloon.clipW[4]
            ]
        else:
            sw = size.width() // 3
            dw = [sw, size.width() - sw * 2, sw]

        if len(self._balloon.clipH) == 3:
            dh = [
                self._balloon.clipH[0],
                size.height() - self._balloon.clipH[0] -
                self._balloon.clipH[2], self._balloon.clipH[2]
            ]
        elif len(self._balloon.clipH) == 5:
            sh = size.height() - self._balloon.clipH[0] - self._balloon.clipH[
                2] - self._balloon.clipH[4]
            dh = [
                self._balloon.clipH[0], sh // 2, self._balloon.clipH[2],
                sh - sh // 2, self._balloon.clipH[4]
            ]
        else:
            sh = size.height() // 3
            dh = [sh, size.height() - sh * 2, sh]

        for y in range(len(self._balloon.clipH)):
            dr = []
            for x in range(len(self._balloon.clipW)):
                pt = QPoint(0, 0)
                if x > 0: pt.setX(dr[x - 1].x() + dw[x - 1])
                if y > 0: pt.setY(drect[y - 1][0].y() + dh[y - 1])
                sz = QSize(dw[x], dh[y])
                dr.append(QRect(pt, sz))
            drect.append(dr)
        pass  # exit for

        # paint balloon image
        img = QImage(size, QImage.Format_ARGB32)
        pixmap = QPixmap().fromImage(self._balloon_image_cache, Qt.AutoColor)
        painter = QPainter(img)
        painter.setCompositionMode(QPainter.CompositionMode_Source)

        for y in range(len(self._balloon.clipH)):
            for x in range(len(self._balloon.clipW)):
                painter.drawPixmap(drect[y][x], pixmap,
                                   self._balloon.bgRect[y][x])
        painter.end()

        # flip or not
        if self._balloon.flipBackground is True and flip is True:
            img = img.mirrored(True, False)
            if self._balloon.noFlipCenter is True and len(
                    self._balloon.clipW) == 5 and len(
                        self._balloon.clipH) == 5:
                painter = QPainter(img)
                painter.setCompositionMode(QPainter.CompositionMode_Source)
                painter.drawPixmap(drect[2][2], pixmap,
                                   self._balloon.bgRect[2][2])
                painter.end()

        # debug draw
        if kikka.shell.isDebug is True:
            painter = QPainter(img)
            painter.fillRect(QRect(0, 0, 200, 64), QColor(0, 0, 0, 64))
            painter.setPen(Qt.red)
            for y in range(len(self._balloon.clipH)):
                for x in range(len(self._balloon.clipW)):
                    if x in (0, 2, 4) and y in (0, 2, 4):
                        continue
                    rectf = QRect(drect[y][x])
                    text = "(%d, %d)\n%d x %d" % (
                        rectf.x(), rectf.y(), rectf.width(), rectf.height())
                    painter.drawText(rectf, Qt.AlignCenter, text)
                if y > 0:
                    painter.drawLine(drect[y][0].x(), drect[y][0].y(),
                                     drect[y][0].x() + img.width(),
                                     drect[y][0].y())

            for x in range(1, len(self._balloon.clipW)):
                painter.drawLine(drect[0][x].x(), drect[0][x].y(),
                                 drect[0][x].x(),
                                 drect[0][x].y() + img.height())

            painter.setPen(Qt.green)
            painter.drawRect(QRect(0, 0, img.width() - 1, img.height() - 1))
            painter.drawText(3, 12, "DialogWindow")
            painter.drawText(3, 24, "Ghost: %d" % self.ID)
            painter.drawText(3, 36, "Name: %s" % self.name)
            painter.drawText(3, 48, "soul_id: %d" % soul_id)
        return img
Exemple #32
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setMouseTracking(True)
        self.coords_ = []
        self.qp = QPainter()
        self.flag = False
        self.status = None

    def drawf(self):
        self.flag = True
        self.update()

    def paintEvent(self, event):
        if self.flag:
            self.qp = QPainter()
            self.qp.begin(self)
            self.setBrushColor()
            self.draw(self.status)
            self.qp.end()

    def setBrushColor(self):
        self.r = random.randint(0, 255)
        self.g = random.randint(0, 255)
        self.b = random.randint(0, 255)
        self.qp.setBrush(QColor(self.r, self.g, self.b))

    def draw(self, status):
        self.size = random.randint(10, 100)
        if status == 1:
            self.qp.drawEllipse(*self.coords_, self.size, self.size)
        elif status == 2:
            self.qp.drawRect(*self.coords_, self.size, self.size)
        elif status == 3:
            x, y = self.coords_
            self.qp.drawPolygon(
                QPolygon([
                    QPoint(x, y - self.size),
                    QPoint(x + self.size, y + self.size),
                    QPoint(x - self.size, y + self.size)
                ]))

    def initUI(self):
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Рисование')

        self.show()

    def mousePressEvent(self, event):
        self.coords_ = [event.x(), event.y()]
        if event.button() == Qt.LeftButton:
            self.status = 1
        elif event.button() == Qt.RightButton:
            self.status = 2
        self.drawf()

    def mouseMoveEvent(self, event):
        self.coords_ = [event.x(), event.y()]

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            self.status = 3
        self.drawf()
    def paintEvent(self, event):
        # Init painter.
        painter = QPainter(self)
        painter.save()

        # Draw background.
        background_color = self.background_color
        if self.inverted_mode:  # change color of background if inverted mode is enable
            background_color = QColor(20, 20, 20, 255)
        painter.setBrush(background_color)
        painter.setPen(background_color)
        painter.drawRect(0, 0, self.rect().width(), self.rect().height())

        # Get start/last render index.
        start_page_index = self.get_start_page_index()
        last_page_index = self.get_last_page_index()

        # Translate painter at y coordinate.
        translate_y = (start_page_index * self.scale *
                       self.page_height) - self.scroll_offset
        painter.translate(0, translate_y)

        # Render pages in visible area.
        for index in list(range(start_page_index, last_page_index)):
            if index < self.page_total_number:
                # Get page image.
                qpixmap = self.get_page_pixmap(index, self.scale)

                # Init render rect.
                render_width = self.page_width * self.scale
                render_height = self.page_height * self.scale
                render_x = (self.rect().width() - render_width) / 2
                render_y = (index -
                            start_page_index) * self.scale * self.page_height

                # Add padding between pages.
                if (index - start_page_index) > 0:
                    painter.translate(0, self.page_padding)

                # Draw page image.
                painter.drawPixmap(
                    QRect(render_x, render_y, render_width, render_height),
                    qpixmap)

        # Clean unused pixmap cache that avoid use too much memory.
        self.clean_unused_page_cache_pixmap()

        painter.restore()

        # Render current page.
        painter.setFont(self.font)

        if self.inverted_mode:
            painter.setPen(self.page_annotate_dark_color)
        else:
            painter.setPen(self.page_annotate_light_color)

        painter.drawText(
            QRect(
                self.rect().x(),
                self.rect().y() + self.rect().height() -
                self.page_annotate_height - self.page_annotate_padding_bottom,
                self.rect().width() - self.page_annotate_padding_right,
                self.page_annotate_height), Qt.AlignRight,
            "{0}% ({1}/{2})".format(
                int((start_page_index + 1) * 100 / self.page_total_number),
                start_page_index + 1, self.page_total_number))
Exemple #34
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.model = Model()
        self.console = Console(model=self.model, parent=self)
        self.console.move(0, 500)
        self.console.resize(900, 100)
        self.canvas = Canvas(parent=self, model=self.model)
        self.canvas.resize(900, 500)
        self.brushes = []
        self.brushundertypes = {}
        self.brushtype = "point"
        self.brushundertype = "point"
        self.flag = False
        self.lastname = -1
        self.pointCoords = []
        self.fieldWidth = 900
        self.fieldHeight = 635
        self.zoomValue = 100
        self.operations = []
        self.programTitle = "Prototype"

        self.select = list()
        self.table = False

        self.initUI()

    def newPoint(self, x: float, y: float, alloperationsInserting=True):
        point = self.model.add_point(x, y)
        self.model.operations.append(geometry.Point(x, y))
        if alloperationsInserting:
            self.model.alloperations.append(geometry.Point(x, y))
        return point

    def newSegment(self,
                   pointstart: geometry.Point,
                   pointend: geometry.Point,
                   alloperationsInserting=True):
        segment = self.model.check_segment(pointstart, pointend)
        self.model.operations.append(geometry.Segment(pointstart, pointend))
        if alloperationsInserting:
            self.model.alloperations.append(
                geometry.Segment(pointstart, pointend))
        return segment

    def newCircle(self,
                  segment: geometry.Segment,
                  alloperationsInserting=True):
        circle = self.model.check_circle(segment)
        self.model.operations.append(geometry.Circle(segment))
        if alloperationsInserting:
            self.model.alloperations.append(geometry.Circle(segment))
        return circle

    def newBrush(self, brush):
        self.brushes.append(brush)

    def newUnderType(self, brush, brushundertype):
        try:
            self.brushundertypes[brush].append(brushundertype)
        except:
            self.brushundertypes[brush] = [brushundertype]

    def messageSend(self, message):
        self.statusBar().showMessage(message)

    def brushMessage(self):
        self.messageSend("Brush Type is \"" + self.brushtype + "\"")

    def undertypeMessage(self):
        self.messageSend("Brush Type is \"" + self.brushtype + "\"" +
                         " " * 10 + "Brush UnderType is \"" +
                         self.brushundertype + "\"")

    def setBrushType(self, typeOfBrush, brushObject):
        self.pointCoords = []
        for brush in self.brushes:
            for action in self.brushundertypes[brush]:
                self.toolbar.removeAction(action)
        self.brushtype = typeOfBrush
        self.brushMessage()
        self.select = list()
        for brush in self.brushes:
            brush.setChecked(False)
        brushObject.setChecked(True)
        self.undertypeBrushes.clear()
        for action in self.brushundertypes[brushObject]:
            self.undertypeBrushes.addAction(action)
            self.toolbar.addAction(action)
            action.setChecked(False)
        if self.brushtype == "point":
            self.brushundertype = "point"
            self.pointPointBrush.setChecked(True)
        elif self.brushtype == "segment":
            self.brushundertype = "segment"
            self.segmentSegmentBrush.setChecked(True)
        elif self.brushtype == "circle":
            self.brushundertype = "radius"
            self.circleRadiusBrush.setChecked(True)
        elif self.brushtype == "congruency":
            self.brushundertype = "congruency"
            self.congruencyNormalBrush.setChecked(True)

    def setUnderType(self, typeOfUnderType, underTypeObject, brushObject):
        self.brushundertype = typeOfUnderType
        self.undertypeMessage()
        for undertype in self.brushundertypes[brushObject]:
            undertype.setChecked(False)
        underTypeObject.setChecked(True)

    def zoom(self, value):
        if value == 0:
            self.zoomValue = 100
        elif self.zoomValue < abs(value) and value < 0 or value > 0:
            self.zoomValue += value

    def reset(self):
        self.pointCoords = []
        self.select = list()

    def addCongruency(self):
        if not self.select:
            return
        s = self.select[0]
        for segment in self.select:
            if segment is not s:
                segment1 = f'segment({segment.point1.name}, {segment.point2.name})'
                segment2 = f'segment({s.point1.name}, {s.point2.name})'
                self.model.translator.connector.prolog.assertz(
                    f'congruent({segment1}, {segment2})')
                s = segment
        self.model.updateCongruencyClasses()

    def fixScheme(self):
        self.model.correctingScheme()
        self.model.updateEverything()
        self.update()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.flag = True
        elif event.button() == Qt.RightButton:
            self.update()

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_QuoteLeft:
            self.console.show()

    def mouseReleaseEvent(self, event):
        self.update()

    def centering(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def clear(self):
        self.model.reset_prolog()
        self.paint = QPainter(self.image)
        self.paint.setBrush(QBrush(self.canvas.backgroundColor))
        self.select = list()
        self.model.points = {}
        self.model.circles = {}
        self.model.segments = {}
        self.model.dependpoints = {}
        self.model.circles = {}
        self.paint.drawRect(-20, 20, self.fieldWidth + 30,
                            self.fieldHeight + 30)

    def reference(self):
        webbrowser.open("reference.html")

    def authors(self):
        pass

    def fileActionsCreating(self):
        self.newFileAct = QAction("&New", self)
        self.newFileAct.setShortcut("Ctrl+N")
        self.newFileAct.setStatusTip("Creating New File")
        self.newFileAct.setToolTip("Creating <b>New</b> File")
        self.newFileAct.triggered.connect(self.clear)

        self.quitAct = QAction("&Quit", self)
        self.quitAct.setShortcut("Ctrl+Q")
        self.quitAct.setStatusTip("Quit program")
        self.quitAct.setToolTip("<b>Quit</b> program")
        self.quitAct.triggered.connect(qApp.quit)

    def pointBrushActionsCreating(self):
        self.pointBrush = QAction("&Point", self, checkable=True)
        self.pointBrush.setShortcut("Ctrl+1")
        self.pointBrush.setStatusTip("Take Point Brush")
        self.pointBrush.setToolTip("Take <b>Point</b> Brush")
        self.pointBrush.triggered.connect(
            lambda event: self.setBrushType("point", self.pointBrush))
        self.pointBrush.setChecked(True)
        self.newBrush(self.pointBrush)

        self.pointPointBrush = QAction("&Point", self, checkable=True)
        self.pointPointBrush.setStatusTip("Making Point")
        self.pointPointBrush.setToolTip("Making <b>Point</b>")
        self.pointPointBrush.triggered.connect(lambda event: self.setUnderType(
            "point", self.pointPointBrush, self.pointBrush))
        self.pointPointBrush.setChecked(True)
        self.newUnderType(self.pointBrush, self.pointPointBrush)

        self.pointInObjectBrush = QAction("&Point In Object",
                                          self,
                                          checkable=True)
        self.pointInObjectBrush.setStatusTip("Making Point In Object")
        self.pointInObjectBrush.setToolTip("Making <b>Point In Object</b>")
        self.pointInObjectBrush.triggered.connect(
            lambda event: self.setUnderType(
                "pointinobject", self.pointInObjectBrush, self.pointBrush))
        self.pointInObjectBrush.setChecked(False)
        self.newUnderType(self.pointBrush, self.pointInObjectBrush)

    def segmentBrushActionsCreating(self):
        self.segmentBrush = QAction("&Segment", self, checkable=True)
        self.segmentBrush.setShortcut("Ctrl+2")
        self.segmentBrush.setStatusTip("Take Segment Brush")
        self.segmentBrush.setToolTip("Take <b>Segment</b> Brush")
        self.segmentBrush.triggered.connect(
            lambda event: self.setBrushType("segment", self.segmentBrush))
        self.segmentBrush.setChecked(False)
        self.newBrush(self.segmentBrush)

        self.segmentSegmentBrush = QAction("&Segment", self, checkable=True)
        self.segmentSegmentBrush.setStatusTip("Making Segment")
        self.segmentSegmentBrush.setToolTip("Making <b>Segment</b>")
        self.segmentSegmentBrush.triggered.connect(
            lambda event: self.setUnderType(
                "segment", self.segmentSegmentBrush, self.segmentBrush))
        self.segmentSegmentBrush.setChecked(True)
        self.newUnderType(self.segmentBrush, self.segmentSegmentBrush)

    def circlesBrushActionsCreating(self):
        self.circleBrush = QAction("&Circle", self, checkable=True)
        self.circleBrush.setShortcut("Ctrl+3")
        self.circleBrush.setStatusTip("Take Circle Brush")
        self.circleBrush.setToolTip("Take <b>Circle</b> Brush")
        self.circleBrush.triggered.connect(
            lambda event: self.setBrushType("circle", self.circleBrush))
        self.circleBrush.setChecked(False)
        self.newBrush(self.circleBrush)

        self.circleRadiusBrush = QAction("&Radius", self, checkable=True)
        self.circleRadiusBrush.setStatusTip("Making Circle With Radius")
        self.circleRadiusBrush.setToolTip("Making Circle With <b>Radius</b>")
        self.circleRadiusBrush.triggered.connect(
            lambda event: self.setUnderType("radius", self.circleRadiusBrush,
                                            self.circleBrush))
        self.circleRadiusBrush.setChecked(True)
        self.newUnderType(self.circleBrush, self.circleRadiusBrush)

    def congruencyBrushActionCreating(self):
        self.congruencyBrush = QAction("&Congruency", self, checkable=True)
        self.congruencyBrush.setShortcut("Ctrl+4")
        self.congruencyBrush.setStatusTip("Set congruency")
        self.congruencyBrush.setToolTip("Set <b>congruency</b>")
        self.congruencyBrush.triggered.connect(lambda event: self.setBrushType(
            "congruency", self.congruencyBrush))
        self.congruencyBrush.setChecked(False)
        self.newBrush(self.congruencyBrush)

        self.congruencyNormalBrush = QAction("&Congruency",
                                             self,
                                             checkable=True)
        self.congruencyNormalBrush.setStatusTip("Set congruency")
        self.congruencyNormalBrush.setToolTip("Set <b>congruency</b>")
        self.congruencyNormalBrush.triggered.connect(
            lambda event: self.setUnderType(
                "congruency", self.congruencyNormalBrush, self.congruencyBrush)
        )
        self.congruencyNormalBrush.setChecked(True)
        self.newUnderType(self.congruencyBrush, self.congruencyNormalBrush)

    def editActionsCreating(self):

        self.resetCommand = QAction("&Reset", self)
        self.resetCommand.setShortcut("Ctrl+R")
        self.resetCommand.setStatusTip("Reset point")
        self.resetCommand.setToolTip("<b>Reset</b> point")
        self.resetCommand.triggered.connect(self.reset)

        self.addCongruencyCommand = QAction("Add Con&gruency", self)
        self.addCongruencyCommand.setShortcut("Ctrl+G")
        self.addCongruencyCommand.setStatusTip("Congruency added")
        self.addCongruencyCommand.setToolTip("<b>Add Congruency</b>")
        self.addCongruencyCommand.triggered.connect(self.addCongruency)

        self.fixSchemeCommand = QAction("Fix Scheme", self)
        self.fixSchemeCommand.setShortcut("Ctrl+Space")
        self.fixSchemeCommand.setStatusTip("Oops")
        self.fixSchemeCommand.setToolTip("<b>Fix Scheme</b>")
        self.fixSchemeCommand.triggered.connect(self.fixScheme)

    def viewActionsCreating(self):
        self.backgroundColorCommand = QAction("&Background", self)
        self.backgroundColorCommand.setShortcut("Alt+B")
        self.backgroundColorCommand.setStatusTip(
            "Change your background color")
        self.backgroundColorCommand.setToolTip(
            "Change your <b>background color</b>")
        self.backgroundColorCommand.triggered.connect(
            self.canvas.backgroundColorSelect)

        self.foregroundPointColorCommand = QAction("&Foreground Point", self)
        self.foregroundPointColorCommand.setShortcut("Alt+P")
        self.foregroundPointColorCommand.setStatusTip(
            "Change your point color")
        self.foregroundPointColorCommand.setToolTip(
            "Change your <b>point color</b>")
        self.foregroundPointColorCommand.triggered.connect(
            self.canvas.foregroundPointColorSelect)

        self.foregroundDependingPointColorCommand = QAction(
            "&Foreground Depending Point", self)
        self.foregroundDependingPointColorCommand.setShortcut("Alt+D")
        self.foregroundDependingPointColorCommand.setStatusTip(
            "Change your depending point color")
        self.foregroundDependingPointColorCommand.setToolTip(
            "Change your <b>depending point color</b>")
        self.foregroundDependingPointColorCommand.triggered.connect(
            self.canvas.foregroundDependingPointColorSelect)

        self.foregroundSegmentColorCommand = QAction("&Foreground Segment",
                                                     self)
        self.foregroundSegmentColorCommand.setShortcut("Alt+S")
        self.foregroundSegmentColorCommand.setStatusTip(
            "Change your segment color")
        self.foregroundSegmentColorCommand.setToolTip(
            "Change your <b>segment color</b>")
        self.foregroundSegmentColorCommand.triggered.connect(
            self.canvas.foregroundSegmentColorSelect)

        self.foregroundTextColorCommand = QAction("&Foreground Text", self)
        self.foregroundTextColorCommand.setShortcut("Alt+T")
        self.foregroundTextColorCommand.setStatusTip("Change your text color")
        self.foregroundTextColorCommand.setToolTip(
            "Change your <b>text color</b>")
        self.foregroundTextColorCommand.triggered.connect(
            self.canvas.foregroundTextColorSelect)

        self.foregroundSelectionSegmentsCommand = QAction(
            "&Foreground Selecting Segments", self)
        self.foregroundSelectionSegmentsCommand.setShortcut("Alt+C")
        self.foregroundSelectionSegmentsCommand.setStatusTip(
            "Change your selecting segments color")
        self.foregroundSelectionSegmentsCommand.setToolTip(
            "Change your <b>selecting segments color</b>")
        self.foregroundSelectionSegmentsCommand.triggered.connect(
            self.canvas.foregroundSelectionSegmentsSelect)

        self.textFontCommand = QAction("&Font Text", self)
        self.textFontCommand.setStatusTip("Change your font")
        self.textFontCommand.setToolTip("Change your <b>font</b>")
        self.textFontCommand.triggered.connect(self.canvas.fontSelect)

    def helpActionsCreating(self):
        self.referenceCommand = QAction("&Reference", self)
        self.referenceCommand.setShortcut("F1")
        self.referenceCommand.setStatusTip("Reference show")
        self.referenceCommand.setToolTip("<b>Reference</b> show")
        self.referenceCommand.triggered.connect(self.reference)

        self.authorsCommand = QAction("&Authors", self)
        self.authorsCommand.setStatusTip("Authors show")
        self.authorsCommand.setToolTip("<b>Authors</b> show")
        self.authorsCommand.triggered.connect(self.authors)

    def menuCreating(self):
        self.menubar = self.menuBar()
        self.fileMenu = self.menubar.addMenu("&File")
        self.fileMenu.addAction(self.newFileAct)

        self.brushesMenu = self.menubar.addMenu("&Brushes")
        self.typeBrushes = QMenu("&Brush Types", self)
        self.undertypeBrushes = QMenu("&Brush Under Types", self)
        self.brushesMenu.addMenu(self.typeBrushes)
        self.brushesMenu.addMenu(self.undertypeBrushes)

        self.typeBrushes.addAction(self.pointBrush)
        self.typeBrushes.addAction(self.segmentBrush)
        self.typeBrushes.addAction(self.circleBrush)
        self.typeBrushes.addAction(self.congruencyBrush)

        self.undertypeBrushes.addAction(self.pointPointBrush)
        self.undertypeBrushes.addAction(self.pointInObjectBrush)

        self.editMenu = self.menubar.addMenu("&Edit")
        self.editMenu.addAction(self.resetCommand)
        self.editMenu.addAction(self.addCongruencyCommand)
        self.editMenu.addAction(self.fixSchemeCommand)

        self.viewMenu = self.menubar.addMenu("&View")
        self.foregroundMenu = QMenu("&Foreground", self)
        self.viewMenu.addAction(self.backgroundColorCommand)
        self.viewMenu.addMenu(self.foregroundMenu)
        self.foregroundMenu.addAction(self.foregroundPointColorCommand)
        self.foregroundMenu.addAction(
            self.foregroundDependingPointColorCommand)
        self.foregroundMenu.addAction(self.foregroundSegmentColorCommand)
        self.foregroundMenu.addAction(self.foregroundTextColorCommand)
        self.foregroundMenu.addAction(self.foregroundSelectionSegmentsCommand)
        self.viewMenu.addAction(self.textFontCommand)

        self.helpMenu = self.menubar.addMenu("&Help")
        self.helpMenu.addAction(self.referenceCommand)
        self.helpMenu.addAction(self.authorsCommand)

    def toolbarFilling(self):
        self.toolbar = self.addToolBar("Toolbar")
        self.toolbar.setMovable(False)
        self.toolbar.setToolTip("<b>Toolbar</b>")
        self.toolbar.setStatusTip("Toolbar")
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.pointBrush)
        self.toolbar.addAction(self.segmentBrush)
        self.toolbar.addAction(self.circleBrush)
        self.toolbar.addAction(self.congruencyBrush)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.resetCommand)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.newFileAct)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.quitAct)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.addCongruencyCommand)
        self.toolbar.addSeparator()

    def initUI(self):
        self.setFixedSize(self.fieldWidth, self.fieldHeight)
        self.saveState()
        self.setWindowTitle(self.programTitle)
        self.show()
        self.centering()

        self.image = QImage(self.width(), self.height(), QImage.Format_ARGB32)
        self.image.fill(QColor(64, 0, 128))

        self.setToolTip("<b>Drawing Place</b>")

        self.fileActionsCreating()
        self.pointBrushActionsCreating()
        self.segmentBrushActionsCreating()
        self.circlesBrushActionsCreating()
        self.congruencyBrushActionCreating()
        self.editActionsCreating()
        self.viewActionsCreating()
        self.helpActionsCreating()
        self.menuCreating()
        self.toolbarFilling()

        QApplication.setOverrideCursor(Qt.CrossCursor)

        QApplication.setOverrideCursor(Qt.CrossCursor)

        self.setBrushType("point", self.pointBrush)
        self.messageSend("Paint")
Exemple #35
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        
        # Reset box
        qp.setPen(Qt.NoPen)
        qp.setBrush(self.brushes[1024])
        qp.drawRoundedRect(self.resetRect, 5, 5)
        qp.setPen(QColor(0xf9f6f2))
        qp.setFont(QFont("Tahoma", 25))
        qp.drawText(self.resetRect, "Reset", QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        
        # Description
        qp.setPen(QColor(0x776e65))
        qp.setFont(QFont("Tahoma", 12))
        qp.drawText(self.descriptionRect, "2048 auto player\nwith Parallel Terraced Scan applied", QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        
        # Titles left (game)
        for i in range(4):
            for j in range(4):
                rect = QRectF(j * 100, 100 + i * 100, 100, 100)
                qp.setPen(Qt.NoPen)
                # qp.setBrush(QColor(255,80,0,160))
                qp.setBrush(self.brushes[self.player1.game1.chessboard[i, j]])
                qp.drawRect(rect)
                
                if self.player1.game1.chessboard[i, j] < 10:
                    qp.setPen(QColor(0x776e65))
                else:
                    qp.setPen(QColor(0xf9f6f2))
                if self.player1.game1.chessboard[i, j] > 999:
                    qp.setFont(QFont("Tahoma", 30))
                elif self.player1.game1.chessboard[i, j] > 99:
                    qp.setFont(QFont("Tahoma", 40))
                else: # 1 or 2 digits
                    qp.setFont(QFont("Tahoma", 50))
                if self.player1.game1.chessboard[i, j] != 0:
                    qp.drawText(rect, str(self.player1.game1.chessboard[i, j]), QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))           
                
        # Titles right (perception space)
        borderRect =QRectF(400,100,400,400)
        qp.setPen(QColor(0xffffff)) # the black border
        qp.setBrush(QColor(0xffffff)) # the white background
        qp.drawRect(borderRect)
        
        # Draw perception space
        for i in range(4):
            for j in range(4):
                rect = QRectF(400 + j * 100, 100 + i * 100, 100, 100)
                
                if self.player1.controller1.workspace1.perceptionSpace[i,j] != 0:
                    qp.setPen(QColor(0x000000))
                    qp.setBrush(QColor(128,128,128,30))
                    qp.drawRect(rect)
                
                qp.setPen(QColor(0x000000))
                if self.player1.controller1.workspace1.perceptionSpace[i, j] > 999:
                    qp.setFont(QFont("Tahoma", 30))
                elif self.player1.controller1.workspace1.perceptionSpace[i, j] > 99:
                    qp.setFont(QFont("Tahoma", 40))
                elif self.player1.controller1.workspace1.perceptionSpace[i, j] > 9:
                    qp.setFont(QFont("Tahoma", 50))

        # Draw newly added structure
        # Draw titles
        if self.infoFromSignal != [] and type(self.infoFromSignal[0][1])==int:
            cordinate = self.infoFromSignal[0]
            structureRect = QRectF(400 + cordinate[1]*100, 100 + cordinate[0]*100, 100,100)
            qp.setFont(self.len2Font(str(self.infoFromSignal[1])))
            qp.setPen(QColor(0x999999))
            text = str(self.infoFromSignal[1])
            #print("This is the TEXT!  "+text)
            qp.drawText(structureRect,text,QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        # TODO: Draw relation
        
        # Draw concepts
        for i in range(len(self.conceptFromSignal)):
            #print('Drawing Concepts')
            conceptRect = QRectF(801,100+20*i,120,20)
            qp.setPen(QColor(0x999999))
            qp.setBrush(QColor(0xffffff))
            qp.drawRect(conceptRect)
            conceptActivityRect = QRectF(801,100+20*i,self.conceptFromSignal[i][1]*10,20)
            qp.setPen(Qt.NoPen)
            qp.setBrush(QColor(0xf2b179))
            qp.drawRect(conceptActivityRect)
            qp.setPen(QColor(0x000000))
            qp.setFont(QFont("Tahoma",15))
            qp.drawText(conceptRect,str(self.conceptFromSignal[i][0]),QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        
        # Draw coderack stat
        if len(self.codeRackStatFromSignal) > 0:
            statRect = QRectF(401,15,400,40)
            qp.setPen(QColor(0x555555))
            qp.setFont(QFont("Tahoma",20))
            statText=''
            if len(self.codeRackStatFromSignal[1]) > 0:
                for i in self.codeRackStatFromSignal[1]:
                    statText += str(i)+': '+str(self.codeRackStatFromSignal[0][i])+'  '
                    qp.drawText(statRect,statText)
        
        # Draw proposal activities
        upRect = QRectF(800,15,20,20)
        downRect = QRectF(800,35,20,20)
        leftRect = QRectF(780,35,20,20)
        rightRect = QRectF(820,35,20,20)
        dirRect = {0:upRect,1:downRect,2:leftRect,3:rightRect}
        if len(self.proposalsActivityFromSignal) > 0:
            for proposal in range(4):
                qp.setBrush(QColor(0xffffff))
                qp.drawRect(dirRect[proposal])
                if proposal in self.proposalsActivityFromSignal:
                    qp.setPen(QColor(0x000000))
                    qp.drawText(dirRect[proposal],str(self.proposalsActivityFromSignal[proposal]),QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        
        # Draw stuctures
        strcTypeColor = {'same':Qt.gray, 'next':Qt.yellow}
        if len(self.structureDepictList) > 0:
            for strc in self.structureDepictList:
                pen = QPen(strcTypeColor[strc[4]], 2, Qt.SolidLine)
                qp.setPen(pen)
                qp.drawLine(strc[0],strc[1],strc[2],strc[3])
                            
        
        qp.end()
Exemple #36
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("SNAKE!")
        self.window_width = 1600
        self.window_height = 900
        self.game_width = 900
        self.game_height = 900
        self.resize(self.window_width, self.window_height)

        # Center the window
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        self.centralWidget = QWidget(self)
        self.setCentralWidget(self.centralWidget)

        self.label = QLabel()
        self.label.resize(self.game_width, self.game_height)
        self.label.setMaximumWidth(900)
        self.label.setStyleSheet("border: 5px solid black;")

        self.settings = Settings(self)
        self.settings.setMaximumWidth(200)

        self.hbox = QHBoxLayout(self.centralWidget)
        self.hbox.addWidget(self.settings)
        self.hbox.addWidget(self.label)

        self.centralWidget.setLayout(self.hbox)
        self.initialize()

    def user_input(self):
        d = QDialog()
        d.setWindowTitle("Settings")

        # kann der Dialog umgangen werden um andere Fenster zu bedienen?
        d.setWindowModality(Qt.ApplicationModal)  # nein (Standard)
        # d.setWindowModality(qc.Qt.WindowModal)    # ja

        # ... wie QWidget verwendbar
        fbox = QFormLayout()

        input_name = QLineEdit()
        fbox.addRow("Name:", input_name)

        btnok = QPushButton("Start the Game", d)
        btnno = QPushButton("Nee, lieber doch nicht!", d)
        fbox.addRow(btnok, btnno)

        d.setLayout(fbox)

        # akzeptieren / ablehnen
        btnok.clicked.connect(lambda: d.accept())
        btnno.clicked.connect(lambda: d.reject())

        # bei Fehler / Erfolg an Hauptfenster melden
        d.accepted.connect(lambda: self.close())
        d.rejected.connect(lambda: self.quit())

        # Extras
        btnok.setDefault(True)  # btn wird bei Enter gedrückt
        d.exec_()

    def initialize(self):
        self.user_input()
        # self.settings.hide()

        tile_width = self.game_width / self.settings.game_size.value()
        self.snake = Snake(0, 0, tile_width)

        self.fruit = Fruit(56.25, 56.25, tile_width)
        self.fruit.new_position(self.game_width,
                                self.settings.game_size.value())

        self.canvas = QImage(self.game_width, self.game_height,
                             QImage.Format_RGBA8888)
        # self.canvas.setStyleSheet("border: 5px solid black;")
        self.background = QImage(self.game_width, self.game_height,
                                 QImage.Format_RGBA8888)
        self.snake_ebene = QImage(self.game_width, self.game_height,
                                  QImage.Format_RGBA8888)
        self.fruit_ebene = QImage(tile_width, tile_width,
                                  QImage.Format_RGBA8888)

        self.timer = QTimer()
        self.timer.setInterval(0)
        self.timer.timeout.connect(self.update)
        self.timer.start(300)

        ## Painter & Brush
        self.painter_canvas = QPainter(self.canvas)
        self.painter_background = QPainter(self.background)
        self.painter_snake = QPainter(self.snake_ebene)
        self.painter_fruit = QPainter(self.fruit_ebene)

        self.brush = QBrush()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Q:
            self.close()

        if e.key() == Qt.Key_O:
            if self.settings.hidden:
                self.settings.show()
                self.settings.hidden = not self.settings.hidden
            else:
                self.settings.hide()
                self.settings.hidden = not self.settings.hidden

        if e.key() == Qt.Key_Escape or e.key() == Qt.Key_P:
            if self.timer.isActive:
                self.timer.stop()
            else:
                self.timer.start(0)
            self.timer.isActive = not self.timer.isActive

        if e.key() == Qt.Key_Left or e.key() == Qt.Key_A:
            self.snake.change_dir([-1, 0])
        if e.key() == Qt.Key_Right or e.key() == Qt.Key_D:
            self.snake.change_dir([1, 0])
        if e.key() == Qt.Key_Down or e.key() == Qt.Key_S:
            self.snake.change_dir([0, 1])
        if e.key() == Qt.Key_Up or e.key() == Qt.Key_W:
            self.snake.change_dir([0, -1])

        if e.key() == Qt.Key_E:
            self.snake.add_length()

    def random_color(self):
        r, g, b = random.randint(0, 255), random.randint(0,
                                                         255), random.randint(
                                                             0, 255)
        a = 255
        r, g, b, a = hex(r)[2:], hex(g)[2:], hex(b)[2:], hex(a)[2:]
        if len(r) == 1:
            r = '0' + r
        if len(g) == 1:
            g = '0' + g
        if len(b) == 1:
            b = '0' + b
        if len(a) == 1:
            a = '0' + a
        hex_code = '#' + r + g + b

        return hex_code

    def update(self):
        self.snake.width = self.game_width / self.settings.game_size.value()
        self.snake.vel = self.snake.width

        self.snake.move(self.game_width, self.settings.border.isChecked())

        self.settings.snake_x.setText(str(self.snake.body[0][0]))
        self.settings.snake_y.setText(str(self.snake.body[0][1]))
        self.settings.fruit_x.setText(str(self.fruit.pos[0]))
        self.settings.fruit_y.setText(str(self.fruit.pos[1]))

        if self.snake.body[0] == self.fruit.pos:
            self.fruit.new_position(self.game_width,
                                    self.settings.game_size.value())
            self.snake.add_length()

        self.timer.start(self.snake.width * self.settings.vel.value())
        self.render()

    def draw_canvas(self):
        self.painter_canvas.fillRect(0, 0, self.game_width, self.game_height,
                                     Qt.white)

    def draw_background(self):
        # self.brush.setStyle(Qt.Dense1Pattern)
        self.background.fill(Qt.transparent)
        w = self.game_width / self.settings.game_size.value()
        self.painter_background.setBrush(self.brush)

        color1 = QColor(Qt.green)
        color1.setAlpha(20)
        color2 = QColor(Qt.green)
        color2.setAlpha(100)
        for i in range(self.settings.game_size.value()):
            for j in range(self.settings.game_size.value()):
                # # color = QColor(self.random_color())
                # # color1.setAlpha(random.choice([20, 100]))
                # color1.setAlpha(random.randint(0, 255))
                # self.brush.setColor(color1)
                if (i + j) % 2 == 0:
                    self.brush.setColor(color1)
                else:
                    self.brush.setColor(color2)
                self.painter_background.setBrush(self.brush)
                self.painter_background.drawRect(i * w, j * w, w, w)

    def died(self):
        self.snake.revive()
        d = QDialog()
        d.setWindowTitle("Looser..")

        # kann der Dialog umgangen werden um andere Fenster zu bedienen?
        d.setWindowModality(Qt.ApplicationModal)  # nein (Standard)
        # d.setWindowModality(qc.Qt.WindowModal)    # ja

        # ... wie QWidget verwendbar
        fbox = QFormLayout()

        input_name = QLabel("YOU DIED")
        fbox.addRow("LOOSER", input_name)

        highscore = QLabel(str(self.snake.highscore))
        fbox.addRow("But your highscore was: ", highscore)

        btnok = QPushButton("Restart the Game", d)
        btnno = QPushButton("Quit", d)
        fbox.addRow(btnok, btnno)

        d.setLayout(fbox)

        # akzeptieren / ablehnen
        btnok.clicked.connect(lambda: d.accept())
        btnno.clicked.connect(lambda: d.reject())

        # bei Fehler / Erfolg an Hauptfenster melden
        d.accepted.connect(lambda: self.snake.reset_highscore())
        d.rejected.connect(lambda: self.close())

        # Extras
        btnok.setDefault(True)  # btn wird bei Enter gedrückt
        d.exec_()

    def render(self):
        self.draw_canvas()
        self.draw_background()
        self.snake.draw(self.snake_ebene, self.painter_snake, self.brush)
        self.fruit.draw(self.fruit_ebene, self.painter_fruit, self.brush)
        if self.snake.dead:
            self.died()

        self.painter_canvas.drawImage(0, 0, self.background)
        self.painter_canvas.drawImage(0, 0, self.snake_ebene)
        self.painter_canvas.drawImage(self.fruit.pos[0], self.fruit.pos[1],
                                      self.fruit_ebene)
        self.label.setPixmap(QPixmap.fromImage(self.canvas))
Exemple #37
0
class TropicalViewer(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi('tropical-viewer.ui', self)

        self.current_page = 0
        self.zoomFactor = 2.9
        self.set_size_percent(self.zoomFactor)
        self.open_pdf_file(
            '/home/miguel/Projects/Estadistica/Numerical_Methods_of_Statistics.pdf'
        )

        self.reload_page()

        self.shortcut_next = QShortcut(QKeySequence('N'), self)
        self.shortcut_prev = QShortcut(QKeySequence('B'), self)

        self.shortcut_next.activated.connect(self.next_page)
        self.shortcut_prev.activated.connect(self.prev_page)
        self.scrollArea.reachbottom.connect(self.scroll_bottom)
        self.scrollArea.reachtop.connect(self.scroll_top)
        self.scrollArea.areaSelected.connect(self.extract_text_from_area)
        self.numPageEdit.editingFinished.connect(self.edit_current_page)

    def open_pdf_file(self, pdffile):
        self.pdfdocumentfile = pdffile
        self.document = Poppler.Document.load(self.pdfdocumentfile)
        self.document.setRenderHint(Poppler.Document.TextAntialiasing)

        self.numPagesLabel.setText(str(self.document.numPages()))

    def reload_page(self):
        self.Poppage = self.document.page(self.current_page)
        # self.imgpage = self.Poppage.renderToImage(self.xres, self.yres, 0, 0,468,648)
        self.imgpage = self.Poppage.renderToImage(self.xres, self.yres)
        image = QPixmap(self.imgpage)
        self.pixpage = image
        self.currentpageLabel.setPixmap(image)
        self.currentpageLabel.resize(self.zoomFactor * image.size())
        self.progressBar.setValue(
            int(self.current_page * 100 / self.document.numPages()))

        self.numPageEdit.setText(str(self.current_page))
        # self.search_page_text('computer software')  ###  testing search

    def jump_to_page(self, page):
        self.current_page = page
        self.reload_page()

    def set_size_percent(self, perc):
        self.xres = perc * 72
        self.yres = perc * 72

    def next_page(self):
        if self.current_page != (self.document.numPages() - 1):
            self.jump_to_page(self.current_page + 1)
            self.scrollArea.verticalScrollBar().setValue(0)

    def prev_page(self):
        if self.current_page != 0:
            self.jump_to_page(self.current_page - 1)
            self.scrollArea.verticalScrollBar().setValue(
                self.scrollArea.verticalScrollBar().maximum())

    def adjustRect(self, rect):
        rct = rect.getRect()
        new = []
        for p in rct:
            new.append(p * self.zoomFactor)
        rect = QRectF()
        rect.setRect(new[0], new[1], new[2], new[3])
        return rect

    def search_page_text(self, text):
        result = self.Poppage.search(text)

        # print(result)
        if len(result) > 0:
            for res in result:
                print(res, self.adjustRect(res))

                self.painter = QPainter(self.pixpage)
                self.pen = QPen()
                self.pen.setWidth(1)

                self.painter.setPen(self.pen)
                self.painter.drawRect(res)
                self.currentpageLabel.setPixmap(self.pixpage)
                self.painter.end()

    def search_text(self):
        pass

    def extract_text_from_area(self, rect):
        rect = self.qrect2qrectf(rect)
        # rect = self.adjustRect(rect)
        print(rect)

        text = ''
        for box in self.Poppage.textList():

            wordbox = self.adjustRect(box.boundingBox())
            wordbox = box.boundingBox()
            print(box.text(), wordbox, rect)
            if rect.intersects(wordbox):
                # print(s.text())
                text = text + " " + box.text()
        print(text)

    def qrect2qrectf(self, Rect):
        rec = Rect.getRect()
        recf = [float(r) for r in rec]
        result = QRectF()
        result.setRect(recf[0], recf[1], recf[2], recf[3])
        return result

    # Widget Response Slots
    def scroll_bottom(self):
        self.next_page()

    def scroll_top(self):
        self.prev_page()

    def edit_current_page(self):
        self.current_page = int(self.numPageEdit.text())
        self.reload_page()
Exemple #38
0
 def paintEvent(self, e):
     painter = QPainter(self)
     painter.setPen(QPen(QColor.fromRgbF(0, 0, 0, 1.0), 1, Qt.SolidLine))
     painter.setBrush(
         QBrush(QColor.fromRgbF(255, 255, 255, 0.2), Qt.SolidPattern))
     painter.drawRect(QRect(self.start, self.end))
Exemple #39
0
    def paintEvent(self, event):
        if self.fMeterStyle == self.STYLE_CALF:
            return self.drawCalf(event)

        painter = QPainter(self)
        event.accept()

        width = self.width()
        height = self.height()

        # draw background
        painter.setPen(QPen(self.fMeterBackground, 2))
        painter.setBrush(self.fMeterBackground)
        painter.drawRect(0, 0, width, height)

        if self.fChannelCount == 0:
            return

        meterPad = 0
        meterPos = 0
        meterSize = (height if self.fMeterOrientation == self.HORIZONTAL else
                     width) / self.fChannelCount

        # set pen/brush for levels
        if self.fMeterStyle == self.STYLE_OPENAV:
            colorTrans = QColor(self.fMeterColorBase)
            colorTrans.setAlphaF(0.5)
            painter.setBrush(colorTrans)
            painter.setPen(QPen(self.fMeterColorBase, 1))
            del colorTrans
            meterPad += 2
            meterSize -= 2

        else:
            painter.setPen(QPen(self.fMeterBackground, 0))
            painter.setBrush(self.fMeterGradient)

        # draw levels
        for level in self.fChannelData:
            if level == 0.0:
                meterPos += meterSize + meterPad
                continue

            if self.fMeterOrientation == self.HORIZONTAL:
                painter.drawRect(0, meterPos, int(level * float(width)),
                                 meterSize)
                meterPos += meterSize + meterPad

            elif self.fMeterOrientation == self.VERTICAL:
                painter.drawRect(meterPos, height - int(level * float(height)),
                                 meterSize, height)
                meterPos += meterSize + meterPad

        if not self.fMeterLinesEnabled:
            return

        # draw lines
        if self.fMeterOrientation == self.HORIZONTAL:
            # Variables
            lsmall = float(width)
            lfull = float(height - 1)

            if self.fMeterStyle == self.STYLE_OPENAV:
                painter.setPen(QColor(37, 37, 37, 100))
                painter.drawLine(lsmall * 0.25, 2, lsmall * 0.25, lfull - 2.0)
                painter.drawLine(lsmall * 0.50, 2, lsmall * 0.50, lfull - 2.0)
                painter.drawLine(lsmall * 0.75, 2, lsmall * 0.75, lfull - 2.0)

                if self.fChannelCount > 1:
                    painter.drawLine(1, lfull / 2 - 1, lsmall - 1,
                                     lfull / 2 - 1)

            else:
                # Base
                painter.setBrush(Qt.black)
                painter.setPen(QPen(self.fMeterColorBaseAlt, 1))
                painter.drawLine(lsmall * 0.25, 2, lsmall * 0.25, lfull - 2.0)
                painter.drawLine(lsmall * 0.50, 2, lsmall * 0.50, lfull - 2.0)

                # Yellow
                painter.setPen(QColor(110, 110, 15, 100))
                painter.drawLine(lsmall * 0.70, 2, lsmall * 0.70, lfull - 2.0)
                painter.drawLine(lsmall * 0.83, 2, lsmall * 0.83, lfull - 2.0)

                # Orange
                painter.setPen(QColor(180, 110, 15, 100))
                painter.drawLine(lsmall * 0.90, 2, lsmall * 0.90, lfull - 2.0)

                # Red
                painter.setPen(QColor(110, 15, 15, 100))
                painter.drawLine(lsmall * 0.96, 2, lsmall * 0.96, lfull - 2.0)

        elif self.fMeterOrientation == self.VERTICAL:
            # Variables
            lsmall = float(height)
            lfull = float(width - 1)

            if self.fMeterStyle == self.STYLE_OPENAV:
                painter.setPen(QColor(37, 37, 37, 100))
                painter.drawLine(2, lsmall - (lsmall * 0.25), lfull - 2.0,
                                 lsmall - (lsmall * 0.25))
                painter.drawLine(2, lsmall - (lsmall * 0.50), lfull - 2.0,
                                 lsmall - (lsmall * 0.50))
                painter.drawLine(2, lsmall - (lsmall * 0.75), lfull - 2.0,
                                 lsmall - (lsmall * 0.75))

                if self.fChannelCount > 1:
                    painter.drawLine(lfull / 2 - 1, 1, lfull / 2 - 1,
                                     lsmall - 1)

            else:
                # Base
                painter.setBrush(Qt.black)
                painter.setPen(QPen(self.fMeterColorBaseAlt, 1))
                painter.drawLine(2, lsmall - (lsmall * 0.25), lfull - 2.0,
                                 lsmall - (lsmall * 0.25))
                painter.drawLine(2, lsmall - (lsmall * 0.50), lfull - 2.0,
                                 lsmall - (lsmall * 0.50))

                # Yellow
                painter.setPen(QColor(110, 110, 15, 100))
                painter.drawLine(2, lsmall - (lsmall * 0.70), lfull - 2.0,
                                 lsmall - (lsmall * 0.70))
                painter.drawLine(2, lsmall - (lsmall * 0.82), lfull - 2.0,
                                 lsmall - (lsmall * 0.82))

                # Orange
                painter.setPen(QColor(180, 110, 15, 100))
                painter.drawLine(2, lsmall - (lsmall * 0.90), lfull - 2.0,
                                 lsmall - (lsmall * 0.90))

                # Red
                painter.setPen(QColor(110, 15, 15, 100))
                painter.drawLine(2, lsmall - (lsmall * 0.96), lfull - 2.0,
                                 lsmall - (lsmall * 0.96))
class screenCapForm(QWidget, Ui_screenCapForm):
    def __init__(self, father):
        super(screenCapForm, self).__init__()
        self.setupUi(self)

        # 设置格式
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                            | QtCore.Qt.CustomizeWindowHint)
        # 改变窗口大小
        self.screenRect = QApplication.desktop().screenGeometry()
        self.setFixedSize(self.screenRect.width(), self.screenRect.height())
        self.gv_fullscreen.setFixedSize(self.screenRect.width(),
                                        self.screenRect.height())
        self.l_rec.setFixedSize(self.screenRect.width(),
                                self.screenRect.height())

        # 禁用滚动条
        self.gv_fullscreen.setVerticalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.gv_fullscreen.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)

        # 获取桌面截图
        self.screenPixmap = QApplication.primaryScreen().grabWindow(
            QApplication.desktop().winId())
        self.scene = QGraphicsScene()
        self.scene.addItem(QGraphicsPixmapItem(self.screenPixmap))
        self.gv_fullscreen.setScene(self.scene)

        # 是否截图状态,选取过程中为pending,结束时或者截图前为done
        self.status = 'done'
        self.father = father
        # 画板,画笔
        self.board = QPixmap(self.screenRect.width(), self.screenRect.height())
        self.board.fill(QtCore.Qt.transparent)
        self.painter = QPainter()
        self.from_point = [0, 0]
        self.to_point = [0, 0]
        self.l_rec.setPixmap(self.board)

    def keyPressEvent(self, QKeyEvent):
        if (QKeyEvent.key() == QtCore.Qt.Key_Escape):
            self.close()

    def paintEvent(self, QPaintEvent):
        if (self.status == 'pending'):
            self.painter.begin(self)
            self.drawRec()
            self.l_rec.setPixmap(self.board)
            self.painter.end()

    def closeEvent(self, QCloseEvent):
        self.father.show()

    def mousePressEvent(self, QMouseEvent):
        self.status = 'pending'
        self.from_point = [QMouseEvent.pos().x(), QMouseEvent.pos().y()]

    def mouseMoveEvent(self, QMouseEvent):
        if (self.status == 'pending'):
            self.to_point = [QMouseEvent.pos().x(), QMouseEvent.pos().y()]
            self.update()
            time.sleep(0.1)

    def mouseReleaseEvent(self, QMouseEvent):
        self.status = 'done'
        self.setParentImg()
        self.close()

    def drawRec(self):
        # 填充为透明
        # self.board.fill(QtCore.Qt.red)
        # 设置画笔
        self.painter.setPen(QPen(QtCore.Qt.red, 2, QtCore.Qt.SolidLine))
        # 绘制矩形
        self.painter.drawRect(self.from_point[0], self.from_point[1],
                              self.to_point[0] - self.from_point[0],
                              self.to_point[1] - self.from_point[1])

    def setParentImg(self):
        qimg = self.screenPixmap.toImage()
        cut_qimg = qimg.copy(self.from_point[0], self.from_point[1],
                             self.to_point[0] - self.from_point[0],
                             self.to_point[1] - self.from_point[1])
        cut_pixmap = QPixmap.fromImage(cut_qimg)
        self.father.scene = QGraphicsScene()
        self.father.scene.addItem(QGraphicsPixmapItem(cut_pixmap))
        self.father.gv_display.setScene(self.father.scene)
        self.father.setSize(self.to_point[0] - self.from_point[0],
                            self.to_point[1] - self.from_point[1])
Exemple #41
0
    def draw(self, image):
        qp = QPainter(image)

        qp.fillRect(self.rect, self.drawContext.fill)
        qp.setPen(QPen(self.drawContext.stroke, self.drawContext.width))
        qp.drawRect(self.rect)
Exemple #42
0
    def show(self, data, boxes=None, lines=None, mask=None):

        if mask is None:
            if boxes is not None:
                mask = np.ones(boxes[0].shape)
            elif lines is not None:
                mask = np.ones(lines[0].shape)
            else:
                assert (boxes is None) and (mask is None)


#        if self.name=='mirror':
#            print data[6,6]

        if self.autoscale:
            clim = (data.min(), data.max())
        else:
            clim = self.clim

        cmin, cmax = clim
        downsample = self.downsample
        data = data[::downsample, ::downsample]

        if self.zoomed:
            x_scale = float(data.shape[1]) / float(self.sx)
            y_scale = float(data.shape[0]) / float(self.sy)

            zy1 = int(round(self.zoom_y1 * y_scale))
            zy2 = int(round(self.zoom_y2 * y_scale))
            zx1 = int(round(self.zoom_x1 * x_scale))
            zx2 = int(round(self.zoom_x2 * x_scale))

            #data = data[self.zoom_y1:self.zoom_y2,self.zoom_x1:self.zoom_x2]
            data = data[zy1:zy2, zx1:zx2]

        bmp = np.round(
            np.clip((data.astype(np.float) - cmin) / (cmax - cmin), 0, 1) *
            255).astype(np.uint8)
        sy, sx = bmp.shape
        n_bytes = bmp.nbytes
        bytes_per_line = int(n_bytes / sy)
        image = QImage(bmp, sy, sx, bytes_per_line, QImage.Format_Indexed8)
        if self.colormap is not None:
            image.setColorTable(self.colortable)
        self.pixmap.convertFromImage(image)

        self.label_xoffset = float(self.label.width() -
                                   self.pixmap.width()) / 2.0

        if boxes is not None and self.draw_boxes:
            x1vec, x2vec, y1vec, y2vec = boxes
            pen = QPen()
            pen.setColor(QColor(*ccfg.search_box_color))
            pen.setWidth(ccfg.search_box_thickness)
            painter = QPainter()
            painter.begin(self.pixmap)
            painter.setPen(pen)
            for index, (x1, y1, x2,
                        y2) in enumerate(zip(x1vec, y1vec, x2vec, y2vec)):
                if mask[index]:
                    width = float(x2 - x1 + 1) / float(self.downsample)
                    painter.drawRect(
                        x1 / float(self.downsample) - self.zoom_x1,
                        y1 / float(self.downsample) - self.zoom_y1, width,
                        width)
            painter.end()

        if lines is not None and self.draw_lines:
            x1vec, x2vec, y1vec, y2vec = lines
            pen = QPen()
            pen.setColor(QColor(*ccfg.slope_line_color))
            pen.setWidth(ccfg.slope_line_thickness)
            painter = QPainter()
            painter.begin(self.pixmap)
            painter.setPen(pen)
            for index, (x1, y1, x2,
                        y2) in enumerate(zip(x1vec, y1vec, x2vec, y2vec)):
                if mask[index]:
                    painter.drawLine(
                        QLine(x1 / float(self.downsample) - self.zoom_x1,
                              y1 / float(self.downsample) - self.zoom_y1,
                              x2 / float(self.downsample) - self.zoom_x1,
                              y2 / float(self.downsample) - self.zoom_y1))
            painter.end()

        if sy == self.sy and sx == self.sx:
            self.label.setPixmap(self.pixmap)
        else:
            self.label.setPixmap(self.pixmap.scaled(self.sy, self.sx))
Exemple #43
0
    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10))

        #Button Router
        btnRout = QPushButton("Router", self)
        btnRout.move(30, 50)

        btnESP = QPushButton("ESP-32", self)
        btnESP.move(160, 50)

        btnStp = QPushButton("Stop", self)
        btnStp.move(290, 50)


        btnShwInts = QPushButton("Result", self)
        #btnShwInts = btnStp = QPushButton("Result", self) #when click button, 2 buttons work (stop and Result)
        btnShwInts.move(420, 50)

        btnRout.clicked.connect(self.btnRoutnClicked)
        btnESP.clicked.connect(self.btnESPClicked)
        btnStp.clicked.connect(self.btnStopClicked)
        btnShwInts.clicked.connect(self.btnShwIntsClicked)

        #Size and color for drawing zone
        self._im = QImage(1700, 960, QImage.Format_ARGB32)
        self._im.fill(QColor("white"))

        #Painting of room - rectangle
        painterRect = QPainter(self._im)
        painterRect.setPen(QPen(QColor("#000"), 1, Qt.SolidLine, Qt.RoundCap))
        painterRect.drawRect(100, 100, 100, 800)

        ##History
#
        ## Size and color for drawing zone
        #self._in = QImage(1700, 960, QImage.Format_ARGB32)
        #self._in.fill(QColor("red"))
        #
        ##Color for speed 72Mbps
        #history = QPainter(self._in)
        #history.setPen(QPen(QColor("#439232"), 1, Qt.SolidLine, Qt.RoundCap))
        ##history_72.setBrush(QBrush(QColor("#439232"), Qt.CrossPattern))
        #history.drawRect(400, 100, 100, 800)
#
        ## Color for speed 54Mbps
        #history_54 = QPainter(self._im)
        #history_54.setPen(QPen(QColor("#923243"), 1, Qt.SolidLine, Qt.RoundCap))
        #history_54.setBrush(QBrush(QColor("#923243"), Qt.CrossPattern))
        #history_54.drawRect(50, 150, 50, 50)
#
        ## Color for speed 32Mbps
        #history_32 = QPainter(self._im)
        #history_32.setPen(QPen(QColor("#324392"), 1, Qt.SolidLine, Qt.RoundCap))
        #history_32.setBrush(QBrush(QColor("#324392"), Qt.CrossPattern))
        #history_32.drawRect(50, 200, 50, 50)
#
        ## Color for speed 11Mbps
        #history_11 = QPainter(self._im)
        #history_11.setPen(QPen(QColor("#000"), 1, Qt.SolidLine, Qt.RoundCap))
        #history_11.setBrush(QBrush(QColor("#000"), Qt.CrossPattern))
        #history_11.drawRect(50, 250, 50, 50)
#
        ## Color for speed 6Mbps
        #history_6 = QPainter(self._im)
        #history_6.setPen(QPen(QColor("#000"), 1, Qt.SolidLine, Qt.RoundCap))
        #history_6.setBrush(QBrush(QColor("#000"), Qt.CrossPattern))
        #history_6.drawRect(50, 300, 50, 50)
#
        ## Color for speed 1Mbps
        #history_1 = QPainter(self._im)
        #history_1.setPen(QPen(QColor("#000"), 1, Qt.SolidLine, Qt.RoundCap))
        #history_1.setBrush(QBrush(QColor("#000"), Qt.CrossPattern))
        #history_1.drawRect(50, 350, 50, 50)

        #Size and Title for program window
        self.setFixedSize(1700, 960)
        self.setWindowTitle('Room')

        self.show()
Exemple #44
0
    def paintEvent(self, e):
        super().paintEvent(e)

        painter = QPainter(self)
        rect = QRect(min(self.parent.x0, self.parent.x1),
                     min(self.parent.y0, self.parent.y1),
                     abs(self.parent.x1 - self.parent.x0),
                     abs(self.parent.y1 - self.parent.y0))

        painter.setPen(QPen(Qt.red, 3, Qt.SolidLine))
        painter.drawRect(rect)  # 画框选区
        painter.drawRect(0, 0, self.width(), self.height())  # 画边界框
        painter.setPen(QPen(Qt.red, 10, Qt.SolidLine))
        # 画选框上的八个点移动点
        painter.drawPoint(
            QPoint(
                self.parent.x0,
                min(self.parent.y1, self.parent.y0) +
                abs(self.parent.y1 - self.parent.y0) // 2))
        painter.drawPoint(
            QPoint(
                min(self.parent.x1, self.parent.x0) +
                abs(self.parent.x1 - self.parent.x0) // 2, self.parent.y0))
        painter.drawPoint(
            QPoint(
                self.parent.x1,
                min(self.parent.y1, self.parent.y0) +
                abs(self.parent.y1 - self.parent.y0) // 2))
        painter.drawPoint(
            QPoint(
                min(self.parent.x1, self.parent.x0) +
                abs(self.parent.x1 - self.parent.x0) // 2, self.parent.y1))
        painter.drawPoint(QPoint(self.parent.x0, self.parent.y0))
        painter.drawPoint(QPoint(self.parent.x0, self.parent.y1))
        painter.drawPoint(QPoint(self.parent.x1, self.parent.y0))
        painter.drawPoint(QPoint(self.parent.x1, self.parent.y1))

        x = y = 100
        if self.parent.x1 > self.parent.x0:
            x = self.parent.x0 + 5
        else:
            x = self.parent.x0 - 72
        if self.parent.y1 > self.parent.y0:
            y = self.parent.y0 + 15
        else:
            y = self.parent.y0 - 5
        # 画分辨率
        painter.drawText(
            x, y, '{}x{}'.format(abs(self.parent.x1 - self.parent.x0),
                                 abs(self.parent.y1 - self.parent.y0)))

        painter.setPen(Qt.NoPen)
        # 填充阴影遮罩
        painter.setBrush(QColor(0, 0, 0, 120))
        painter.drawRect(0, 0, self.width(), min(self.parent.y1,
                                                 self.parent.y0))
        painter.drawRect(0, min(self.parent.y1, self.parent.y0),
                         min(self.parent.x1, self.parent.x0),
                         self.height() - min(self.parent.y1, self.parent.y0))
        painter.drawRect(max(self.parent.x1, self.parent.x0),
                         min(self.parent.y1, self.parent.y0),
                         self.width() - max(self.parent.x1, self.parent.x0),
                         self.height() - min(self.parent.y1, self.parent.y0))
        painter.drawRect(
            min(self.parent.x1, self.parent.x0),
            max(self.parent.y1, self.parent.y0),
            max(self.parent.x1, self.parent.x0) -
            min(self.parent.x1, self.parent.x0),
            self.height() - max(self.parent.y1, self.parent.y0))

        # 画放大镜区
        if not (self.parent.painter_tools['drawcircle_on']
                or self.parent.painter_tools['drawrect_bs_on']
                or self.parent.painter_tools['pen_on']
                or self.parent.painter_tools['eraser_on']
                or self.parent.painter_tools['drawtext_on']
                or self.parent.painter_tools['backgrounderaser_on']
                or self.parent.painter_tools['drawpix_bs_on']
                or self.parent.move_rect):

            painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
            if self.parent.mouse_posx > self.width() - 140:
                enlarge_box_x = self.parent.mouse_posx - 140
            else:
                enlarge_box_x = self.parent.mouse_posx + 20
            if self.parent.mouse_posy > self.height() - 140:
                enlarge_box_y = self.parent.mouse_posy - 120
            else:
                enlarge_box_y = self.parent.mouse_posy + 20
            enlarge_rect = QRect(enlarge_box_x, enlarge_box_y, 120, 120)
            painter.drawRect(enlarge_rect)
            painter.drawText(
                enlarge_box_x, enlarge_box_y - 8,
                '({0}x{1})'.format(self.parent.mouse_posx,
                                   self.parent.mouse_posy))
            try:
                painter.setCompositionMode(QPainter.CompositionMode_Source)
                p = self.parent.pixmap()
                larger_pix = p.copy(self.parent.mouse_posx - 60,
                                    self.parent.mouse_posy - 60, 120,
                                    120).scaled(
                                        120 + self.parent.tool_width * 10,
                                        120 + self.parent.tool_width * 10)
                pix = larger_pix.copy(larger_pix.width() / 2 - 60,
                                      larger_pix.height() / 2 - 60, 120, 120)
                painter.drawPixmap(enlarge_box_x, enlarge_box_y, pix)
                painter.setPen(QPen(Qt.white, 1, Qt.SolidLine))
                painter.drawLine(enlarge_box_x, enlarge_box_y + 60,
                                 enlarge_box_x + 120, enlarge_box_y + 60)
                painter.drawLine(enlarge_box_x + 60, enlarge_box_y,
                                 enlarge_box_x + 60, enlarge_box_y + 120)
            except:
                print('draw_enlarge_box fail')
        painter.end()
Exemple #45
0
    def paint_line_numbers(self, event):
        """Paint the line numbers

        For every visible block in the document draw it's corresponding line
        number in the line numbers widget.
        """
        painter = QPainter(self.line_numbers)
        painter.fillRect(event.rect(), Qt.lightGray)

        block = self.firstVisibleBlock()
        block_number = block.blockNumber()

        content_offset = self.contentOffset()

        number_width = (self.line_numbers.width() -
                        self.line_numbers.padding_right)
        number_height = self.fontMetrics().height()

        breakpoint_size = 8
        breakpoint_y_offset = number_height / 2 - breakpoint_size / 2

        while block.isValid():
            # Get the top coordinate of the current block
            # to know where to paint the line number for it
            block_top = (self.blockBoundingGeometry(block).translated(
                content_offset).top())

            if not block.isVisible() or block_top > event.rect().bottom():
                break

            line_number = block_number + 1
            painter.setPen(Qt.black)
            painter.drawText(0, block_top, number_width, number_height,
                             Qt.AlignRight, str(line_number))

            # FIXME: Replace later with a corresponding method call from the
            #        breakpoints module
            block_has_breakpoint = False
            document_path = self.document_model.path
            for breakpoint in pugdebug.Pugdebug.breakpoints:
                if (breakpoint['local_filename'] == document_path
                        and int(breakpoint['lineno']) == line_number):
                    block_has_breakpoint = True
                    break

            # If block has a breakpoint,
            # draw a green rectangle by the line number
            # if the line number matches the current line number
            # make it red, as it is then a breakpoint hit
            if block_has_breakpoint:
                brush = painter.brush()
                brush.setStyle(Qt.SolidPattern)
                if line_number == self.current_line:
                    brush.setColor(Qt.red)
                else:
                    brush.setColor(Qt.darkGreen)
                painter.setBrush(brush)
                painter.drawRect(
                    QRect(0, block_top + breakpoint_y_offset, breakpoint_size,
                          breakpoint_size))

            block = block.next()
            block_number += 1

        painter.end()
Exemple #46
0
 def paintEvent(self, event):
     super().paintEvent(event)
     rect = QRect(self.x0, self.y0, abs(self.x1 - self.x0), abs(self.y1 - self.y0))
     painter = QPainter(self)
     painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
     painter.drawRect(rect)
Exemple #47
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.save()
        painter.begin(self)
        pen = painter.pen()
        vport = painter.viewport()
        print('hujFrame painter.viewport()', vport)
        painter.drawRect(vport.adjusted(0, 0, -pen.width(), -pen.width()))
        # draw kvadratick in physical coordinates
        # painter.drawRect(0, 0, 100, 100)
        # painter.drawLine(vport.topLeft(), vport.bottomRight())
        # painter.drawLine(vport.bottomLeft(), vport.topRight())
        # print(painter.device().physicalDpiX())
        # print(painter.device().physicalDpiY())
        # print(painter.device().logicalDpiX())
        # print(painter.device().logicalDpiY())
        # was 96.0/72.0   1.4 is some kind of magic number
        scaleDpi = 101.0 / 72.0  # (true res for 344x193 mm, 1366x768) / 72
        LLx = self.graph.boundingBox['LLx']
        LLy = self.graph.boundingBox['LLx']
        URx = self.graph.boundingBox['URx']
        URy = self.graph.boundingBox['URy']
        painter.drawRect(LLx * scaleDpi, LLy * scaleDpi, URx * scaleDpi,
                         URy * scaleDpi)
        print('LLx {0}, LLy {1}, URx {2}, URy {3}'.format(LLx, LLy, URx, URy))
        scale = 96  # maybe this is because GV uses 96 dpi and operates in inches
        for node in self.graph.nodesPtr:
            ng = self.graph.nodeGeometry(node)
            x = ng['centerX'] * scaleDpi
            y = (self.graph.boundingBox['URy'] - ng['centerY']) * scaleDpi
            rx = (ng['width'] / 2) * scale
            ry = (ng['height'] / 2) * scale
            painter.drawEllipse(QPointF(x, y), rx, ry)

            font = painter.font()
            font.setPixelSize(14)
            painter.setFont(font)
            tbox = QRectF(QPointF(x - rx, y - ry), QPointF(x + rx, y + ry))
            label = self.graph.nodeLabel(node)
            boundingRect = painter.drawText(tbox, Qt.AlignCenter,
                                            self.tr(label))

        for edge in self.graph.edgesGeom:
            spl = edge[0]
            if not spl['sflag']:
                start = spl['points'][0]
            else:
                start = spl['sarrowtip']
            if not spl['eflag']:
                end = spl['points'][-1]
            else:
                end = spl['earrowtip']
            x1 = start['x'] * scaleDpi
            y1 = (self.graph.boundingBox['URy'] - start['y']) * scaleDpi
            x2 = end['x'] * scaleDpi
            y2 = (self.graph.boundingBox['URy'] - end['y']) * scaleDpi
            painter.drawLine(x1, y1, x2, y2)

        # font = painter.font()
        # font.setPixelSize(56)
        # painter.setFont(font)
        # rectangle = QRect(0, 0, 100, 50)
        # boundingRect = painter.drawText(rectangle, 0, self.tr("Hello"))
        # pen.setStyle(Qt.DotLine)
        # painter.setPen(pen)
        # painter.drawRect(
        #     boundingRect.adjusted(0, 0, -pen.width(), -pen.width()))
        # pen.setStyle(Qt.DashLine)
        # painter.setPen(pen)
        # painter.drawRect(rectangle.adjusted(0, 0, -pen.width(), -pen.width()))
        painter.restore()
        painter.end()
        del painter
        super(hujFrame, self).paintEvent(event)
Exemple #48
0
    def paintEvent(self, e):
        super().paintEvent(e)
        # 画鼠标位置处的圆
        if 1 in self.parent.painter_tools.values():
            painter = QPainter(self)
            painter.setPen(QPen(self.parent.pencolor, 1, Qt.SolidLine))
            rect = QRectF(self.px - self.parent.tool_width // 2,
                          self.py - self.parent.tool_width // 2,
                          self.parent.tool_width, self.parent.tool_width)
            painter.drawEllipse(rect)
            painter.end()
        if self.startpaint:

            while len(self.parent.eraser_pointlist):  # 画橡皮擦
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                self.pixPainter.setBrush(QColor(0, 0, 0, 0))
                self.pixPainter.setPen(Qt.NoPen)
                self.pixPainter.setCompositionMode(
                    QPainter.CompositionMode_Clear)
                new_pen_point = self.parent.eraser_pointlist.pop(0)
                if self.parent.old_pen[0] != -2 and new_pen_point[0] != -2:
                    self.pixPainter.drawEllipse(
                        new_pen_point[0] - self.parent.tool_width / 2,
                        new_pen_point[1] - self.parent.tool_width / 2,
                        self.parent.tool_width, self.parent.tool_width)

                self.parent.old_pen = new_pen_point
                self.pixPainter.end()

            while len(self.parent.pen_pointlist):  # 画笔功能
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                self.pixPainter.setBrush(self.parent.pencolor)
                self.pixPainter.setPen(
                    QPen(self.parent.pencolor, self.parent.tool_width,
                         Qt.SolidLine))
                new_pen_point = self.parent.pen_pointlist.pop(0)
                if self.parent.old_pen[0] != -2 and new_pen_point[0] != -2:
                    path = QPainterPath(
                        QPoint(self.parent.old_pen[0], self.parent.old_pen[1]))
                    path.quadTo(
                        QPoint(
                            (new_pen_point[0] + self.parent.old_pen[0]) / 2,
                            (new_pen_point[1] + self.parent.old_pen[1]) / 2),
                        QPoint(new_pen_point[0], new_pen_point[1]))
                    self.pixPainter.drawPath(path)
                self.parent.old_pen = new_pen_point
                self.pixPainter.end()

            while len(self.parent.drawpix_pointlist):  # 画马赛克/材质贴图功能
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                brush = QBrush(self.parent.pencolor)
                brush.setTexture(QPixmap(self.pixpng))
                self.pixPainter.setBrush(brush)
                self.pixPainter.setPen(Qt.NoPen)
                new_pen_point = self.parent.drawpix_pointlist.pop(0)
                if self.parent.old_pen[0] != -2 and new_pen_point[0] != -2:
                    self.pixPainter.drawEllipse(
                        new_pen_point[0] - self.parent.tool_width / 2,
                        new_pen_point[1] - self.parent.tool_width / 2,
                        self.parent.tool_width, self.parent.tool_width)

                self.parent.old_pen = new_pen_point
                self.pixPainter.end()

            if self.parent.drawrect_pointlist[0][
                    0] != -2 and self.parent.drawrect_pointlist[1][
                        0] != -2:  # 画方形
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                temppainter = QPainter(self)
                temppainter.setPen(QPen(self.parent.pencolor, 3, Qt.SolidLine))

                poitlist = self.parent.drawrect_pointlist
                temppainter.drawRect(min(poitlist[0][0], poitlist[1][0]),
                                     min(poitlist[0][1], poitlist[1][1]),
                                     abs(poitlist[0][0] - poitlist[1][0]),
                                     abs(poitlist[0][1] - poitlist[1][1]))
                temppainter.end()
                if self.parent.drawrect_pointlist[2] == 1:
                    self.pixPainter.setPen(
                        QPen(self.parent.pencolor, 3, Qt.SolidLine))
                    self.pixPainter.drawRect(
                        min(poitlist[0][0], poitlist[1][0]),
                        min(poitlist[0][1], poitlist[1][1]),
                        abs(poitlist[0][0] - poitlist[1][0]),
                        abs(poitlist[0][1] - poitlist[1][1]))

                    self.parent.drawrect_pointlist = [[-2, -2], [-2, -2], 0]
                self.pixPainter.end()

            if self.parent.drawcircle_pointlist[0][
                    0] != -2 and self.parent.drawcircle_pointlist[1][
                        0] != -2:  # 画圆
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                temppainter = QPainter(self)
                temppainter.setPen(QPen(self.parent.pencolor, 3, Qt.SolidLine))
                poitlist = self.parent.drawcircle_pointlist
                temppainter.drawEllipse(min(poitlist[0][0], poitlist[1][0]),
                                        min(poitlist[0][1], poitlist[1][1]),
                                        abs(poitlist[0][0] - poitlist[1][0]),
                                        abs(poitlist[0][1] - poitlist[1][1]))
                temppainter.end()
                if self.parent.drawcircle_pointlist[2] == 1:
                    self.pixPainter.setPen(
                        QPen(self.parent.pencolor, 3, Qt.SolidLine))
                    self.pixPainter.drawEllipse(
                        min(poitlist[0][0], poitlist[1][0]),
                        min(poitlist[0][1], poitlist[1][1]),
                        abs(poitlist[0][0] - poitlist[1][0]),
                        abs(poitlist[0][1] - poitlist[1][1]))
                    self.parent.drawcircle_pointlist = [[-2, -2], [-2, -2], 0]
                self.pixPainter.end()

            if self.parent.drawarrow_pointlist[0][
                    0] != -2 and self.parent.drawarrow_pointlist[1][
                        0] != -2:  # 画箭头
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                temppainter = QPainter(self)

                poitlist = self.parent.drawarrow_pointlist
                temppainter.translate(poitlist[0][0], poitlist[0][1])
                degree = math.degrees(
                    math.atan2(poitlist[1][1] - poitlist[0][1],
                               poitlist[1][0] - poitlist[0][0]))
                temppainter.rotate(degree)
                dx = math.sqrt((poitlist[1][1] - poitlist[0][1])**2 +
                               (poitlist[1][0] - poitlist[0][0])**2)
                dy = 30
                temppainter.drawPixmap(0, -dy / 2,
                                       QPixmap(':/arrow.png').scaled(dx, dy))

                temppainter.end()
                if self.parent.drawarrow_pointlist[2] == 1:
                    self.pixPainter.translate(poitlist[0][0], poitlist[0][1])
                    degree = math.degrees(
                        math.atan2(poitlist[1][1] - poitlist[0][1],
                                   poitlist[1][0] - poitlist[0][0]))
                    self.pixPainter.rotate(degree)
                    dx = math.sqrt((poitlist[1][1] - poitlist[0][1])**2 +
                                   (poitlist[1][0] - poitlist[0][0])**2)
                    dy = 30
                    self.pixPainter.drawPixmap(
                        0, -dy / 2,
                        QPixmap(':/arrow.png').scaled(dx, dy))
                    self.parent.drawarrow_pointlist = [[-2, -2], [-2, -2], 0]
                    # self.parent.drawarrow_pointlist[0] = [-2, -2]
                self.pixPainter.end()

            if len(self.parent.drawtext_pointlist
                   ) > 1 or self.parent.text_box.paint:  # 画文字
                self.pixPainter = QPainter(self.pixmap())
                self.pixPainter.setRenderHint(QPainter.Antialiasing)
                self.parent.text_box.paint = False
                # print(self.parent.drawtext_pointlist)
                text = self.parent.text_box.toPlainText()
                self.parent.text_box.clear()
                pos = self.parent.drawtext_pointlist.pop(0)
                if text:
                    self.pixPainter.setFont(
                        QFont('微软雅黑', self.parent.tool_width))
                    self.pixPainter.setPen(
                        QPen(self.parent.pencolor, 3, Qt.SolidLine))
                    self.pixPainter.drawText(
                        pos[0] +
                        self.parent.text_box.document.size().height() / 8,
                        pos[1] +
                        self.parent.text_box.document.size().height() * 32 /
                        41, text)

                self.pixPainter.end()
        else:
            self.startpaint = 1
Exemple #49
0
 def paintEvent(self, e):
     """ 根据不同的情况绘制不同的背景 """
     # super().paintEvent(e)
     painter = QPainter(self)
     painter.setRenderHints(QPainter.Antialiasing)
     brush = QBrush(QColor(204, 204, 204))
     painter.setPen(Qt.NoPen)
     if not self.isEnter:
         painter.setBrush(brush)
         painter.drawRoundedRect(self.rect(), 5, 5)
     else:
         painter.setPen(QPen(QColor(204, 204, 204), 2))
         painter.drawRect(1, 1, self.width() - 2, self.height() - 2)
         painter.setPen(Qt.NoPen)
         if not self.pressedPos:
             brush.setColor(QColor(230, 230, 230))
             painter.setBrush(brush)
             painter.drawRect(2, 2, self.width() - 4, self.height() - 4)
         else:
             brush.setColor(QColor(153, 153, 153))
             painter.setBrush(brush)
             # 左上角
             if self.pressedPos == "left-top":
                 points = [
                     QPoint(6, 2),
                     QPoint(self.width() - 1, 1),
                     QPoint(self.width() - 1,
                            self.height() - 1),
                     QPoint(1,
                            self.height() - 1),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
             # 左边
             elif self.pressedPos == "left":
                 painter.drawRoundedRect(6, 1,
                                         self.width() - 7,
                                         self.height() - 2, 3, 3)
             # 左下角
             elif self.pressedPos == "left-bottom":
                 points = [
                     QPoint(1, 1),
                     QPoint(self.width() - 1, 1),
                     QPoint(self.width() - 1,
                            self.height() - 1),
                     QPoint(6,
                            self.height() - 2),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
             # 顶部
             elif self.pressedPos == "top":
                 points = [
                     QPoint(6, 2),
                     QPoint(self.width() - 6, 2),
                     QPoint(self.width() - 1,
                            self.height() - 1),
                     QPoint(1,
                            self.height() - 1),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
             # 中间
             elif self.pressedPos == "center":
                 painter.drawRoundedRect(6, 1,
                                         self.width() - 12,
                                         self.height() - 2, 3, 3)
             # 底部
             elif self.pressedPos == "bottom":
                 points = [
                     QPoint(1, 1),
                     QPoint(self.width() - 1, 1),
                     QPoint(self.width() - 6,
                            self.height() - 2),
                     QPoint(6,
                            self.height() - 2),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
             # 右上角
             elif self.pressedPos == "right-top":
                 points = [
                     QPoint(1, 1),
                     QPoint(self.width() - 6, 2),
                     QPoint(self.width() - 1,
                            self.height() - 1),
                     QPoint(1,
                            self.height() - 1),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
             # 右边
             elif self.pressedPos == "right":
                 painter.drawRoundedRect(1, 1,
                                         self.width() - 7,
                                         self.height() - 2, 3, 3)
             # 右下角
             elif self.pressedPos == "right-bottom":
                 points = [
                     QPoint(1, 1),
                     QPoint(self.width() - 1, 1),
                     QPoint(self.width() - 6,
                            self.height() - 2),
                     QPoint(1,
                            self.height() - 1),
                 ]
                 painter.drawPolygon(QPolygon(points), 4)
 def paint(self, painter: QPainter, styles, widget=None):
     painter.setPen(self.pen)
     painter.setBrush(self.brush)
     painter.drawRect(self.rect)
Exemple #51
0
class Renderer:
    def __init__(self, width, height, ownWindow=False):
        self.width = width
        self.height = height

        self.img = QImage(width, height, QImage.Format_RGB888)
        self.painter = QPainter()

        self.window = None
        if ownWindow:
            self.app = QApplication([])
            self.window = Window()

    def close(self):
        """
        Deallocate resources used
        """
        pass

    def beginFrame(self):
        self.painter.begin(self.img)
        self.painter.setRenderHint(QPainter.Antialiasing, False)

        # Clear the background
        self.painter.setBrush(QColor(0, 0, 0))
        self.painter.drawRect(0, 0, self.width - 1, self.height - 1)

    def endFrame(self):
        self.painter.end()

        if self.window:
            if self.window.closed:
                self.window = None
            else:
                self.window.setPixmap(self.getPixmap())
                self.app.processEvents()

    def getPixmap(self):
        return QPixmap.fromImage(self.img)

    def getArray(self):
        """
        Get a numpy array of RGB pixel values.
        The size argument should be (3,w,h)
        """

        width = self.width
        height = self.height
        shape = (width, height, 3)

        numBytes = self.width * self.height * 3
        buf = self.img.bits().asstring(numBytes)
        output = np.frombuffer(buf, dtype='uint8')
        output = output.reshape(shape)

        return output

    def push(self):
        self.painter.save()

    def pop(self):
        self.painter.restore()

    def rotate(self, degrees):
        self.painter.rotate(degrees)

    def translate(self, x, y):
        self.painter.translate(x, y)

    def scale(self, x, y):
        self.painter.scale(x, y)

    def setLineColor(self, r, g, b, a=255):
        self.painter.setPen(QColor(r, g, b, a))

    def setColor(self, r, g, b, a=255):
        self.painter.setBrush(QColor(r, g, b, a))

    def drawLine(self, x0, y0, x1, y1):
        self.painter.drawLine(x0, y0, x1, y1)

    def drawCircle(self, x, y, r):
        center = QPoint(x, y)
        self.painter.drawEllipse(center, r, r)

    def drawPolygon(self, points):
        """Takes a list of points (tuples) as input"""
        points = map(lambda p: QPoint(p[0], p[1]), points)
        self.painter.drawPolygon(QPolygon(points))

    def fillRect(self, x, y, width, height, r, g, b, a=255):
        self.painter.fillRect(QRect(x, y, width, height), QColor(r, g, b, a))
Exemple #52
0
    def paintEvent(self, event):
        qp = QPainter(self)

        qp.setPen(Qt.black)
        size = self.size()

        # Colored Rectangles
        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(0, 0, 100, 100)

        qp.setBrush(QColor(0, 200, 0))
        qp.drawRect(100, 0, 100, 100)

        qp.setBrush(QColor(0, 0, 200))
        qp.drawRect(200, 0, 100, 100)

        # Color effect
        # Fades from black to Red, Yellow, Green (in that order)
        for i in range(0, 100):
            qp.setBrush(QColor(i * 10, 0, 0))
            qp.drawRect(10 * i, 100, 10, 32)

            qp.setBrush(QColor(i * 10, i * 10, 0))
            qp.drawRect(10 * i, 100 + 32, 10, 32)

            qp.setBrush(QColor(i * 2, i * 10, i * 1))
            qp.drawRect(10 * i, 100 + 64, 10, 32)
Exemple #53
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        #Draw things here
        pen1 = QPen(QBrush(Qt.blue), 6)
        pen2 = QPen(QBrush(Qt.yellow), 6)
        pen3 = QPen(QBrush(Qt.black), 6)
        pen4 = QPen(QBrush(Qt.green), 6)
        pen5 = QPen(QBrush(Qt.red), 6)
        qp.setPen(pen1)
        qp.drawEllipse(105, 100, 95, 95)
        qp.setPen(pen2)
        qp.drawEllipse(160, 160, 95, 95)
        qp.setPen(pen3)
        qp.drawEllipse(215, 100, 95, 95)
        qp.setPen(pen4)
        qp.drawEllipse(270, 160, 95, 95)
        qp.setPen(pen5)
        qp.drawEllipse(325, 100, 95, 95)

        ring = self.event

        if ring == 1:
            qp.setPen(pen1)  #Draw in this color
            qp.setBrush(QBrush(Qt.blue))  #Fill the rectangle in this color
            qp.drawRect(100, 300, 350, 80)

        elif ring == 6:
            qp.setPen(pen1)
            qp.setBrush(QBrush(Qt.blue))
            qp.drawRect(100, 300, 175, 80)
            qp.setPen(pen2)
            qp.setBrush(QBrush(Qt.yellow))
            qp.drawRect(250, 300, 175, 80)

        elif ring == 2:
            qp.setPen(pen2)
            qp.setBrush(QBrush(Qt.yellow))
            qp.drawRect(100, 300, 350, 80)

        elif ring == 7:
            qp.setPen(pen2)
            qp.setBrush(QBrush(Qt.yellow))
            qp.drawRect(100, 300, 175, 80)
            qp.setPen(pen3)
            qp.setBrush(QBrush(Qt.black))
            qp.drawRect(250, 300, 175, 80)

        elif ring == 3:
            qp.setPen(pen3)
            qp.setBrush(QBrush(Qt.black))
            qp.drawRect(100, 300, 350, 80)

        elif ring == 8:
            qp.setPen(pen3)
            qp.setBrush(QBrush(Qt.black))
            qp.drawRect(100, 300, 175, 80)
            qp.setPen(pen4)
            qp.setBrush(QBrush(Qt.green))
            qp.drawRect(250, 300, 175, 80)

        elif ring == 4:
            qp.setPen(pen4)
            qp.setBrush(QBrush(Qt.green))
            qp.drawRect(100, 300, 350, 80)

        elif ring == 9:
            qp.setPen(pen4)
            qp.setBrush(QBrush(Qt.green))
            qp.drawRect(100, 300, 175, 80)
            qp.setPen(pen5)
            qp.setBrush(QBrush(Qt.red))
            qp.drawRect(250, 300, 175, 80)

        elif ring == 5:
            qp.setPen(pen5)
            qp.setBrush(QBrush(Qt.red))
            qp.drawRect(100, 300, 350, 80)

        qp.end()
 def paintEvent(self, e=None):  # pylint: disable=invalid-name, unused-argument, missing-function-docstring
     painter = QPainter(self)
     painter.setPen(Qt.NoPen)
     painter.setBrush(QBrush(QColor(133, 45, 145), Qt.Dense5Pattern))
     painter.drawRect(self.rect())
Exemple #55
0
    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)

        if self.fLabel:
            if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL:
                painter.setPen(self.fLabelGradientColor2)
                painter.setBrush(self.fLabelGradient)
                painter.drawRect(self.fLabelGradientRect)

            painter.setFont(self.fLabelFont)
            painter.setPen(
                self.fLabelGradientColorT[0 if self.isEnabled() else 1])
            painter.drawText(self.fLabelPos, self.fLabel)

        if self.isEnabled():
            normValue = float(self.fRealValue -
                              self.fMinimum) / float(self.fMaximum -
                                                     self.fMinimum)
            target = QRectF(0.0, 0.0, self.fPixmapBaseSize,
                            self.fPixmapBaseSize)

            curLayer = int((self.fPixmapLayersCount - 1) * normValue)

            if self.fPixmapOrientation == self.HORIZONTAL:
                xpos = self.fPixmapBaseSize * curLayer
                ypos = 0.0
            else:
                xpos = 0.0
                ypos = self.fPixmapBaseSize * curLayer

            source = QRectF(xpos, ypos, self.fPixmapBaseSize,
                            self.fPixmapBaseSize)
            painter.drawPixmap(target, self.fPixmap, source)

            # Custom knobs (Dry/Wet and Volume)
            if self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_WET,
                                         self.CUSTOM_PAINT_MODE_CARLA_VOL):
                # knob color
                colorGreen = QColor(0x5D, 0xE7,
                                    0x3D).lighter(100 + self.fHoverStep * 6)
                colorBlue = QColor(0x3E, 0xB8,
                                   0xBE).lighter(100 + self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 216 * 16
                spanAngle = -252 * 16 * normValue

                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_WET:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(
                        QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    gradient = QConicalGradient(15.5, 15.5, -45)
                    gradient.setColorAt(0.0, colorBlue)
                    gradient.setColorAt(0.125, colorBlue)
                    gradient.setColorAt(0.625, colorGreen)
                    gradient.setColorAt(0.75, colorGreen)
                    gradient.setColorAt(0.76, colorGreen)
                    gradient.setColorAt(1.0, colorGreen)
                    painter.setBrush(gradient)
                    painter.setPen(QPen(gradient, 3))

                else:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(
                        QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 3))

                painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (L and R)
            elif self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_L,
                                           self.CUSTOM_PAINT_MODE_CARLA_R):
                # knob color
                color = QColor(0xAD, 0xD5,
                               0x48).lighter(100 + self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(7.0, 8.0, 11.0, 12.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(
                    QRectF(ballPoint.x(), ballPoint.y(), 2.0, 2.0))

                # draw arc
                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_L:
                    startAngle = 216 * 16
                    spanAngle = -252.0 * 16 * normValue
                else:
                    startAngle = 324.0 * 16
                    spanAngle = 252.0 * 16 * (1.0 - normValue)

                painter.setPen(QPen(color, 2))
                painter.drawArc(3.5, 4.5, 22.0, 22.0, startAngle, spanAngle)

            # Custom knobs (Color)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_COLOR:
                # knob color
                color = self.fCustomPaintColor.lighter(100 +
                                                       self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 216 * 16
                spanAngle = -252 * 16 * normValue

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(
                    QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                painter.setBrush(color)
                painter.setPen(QPen(color, 3))
                painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (Zita)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_ZITA:
                a = normValue * pi * 1.5 - 2.35
                r = 10.0
                x = 10.5
                y = 10.5
                x += r * sin(a)
                y -= r * cos(a)
                painter.setBrush(Qt.black)
                painter.setPen(QPen(Qt.black, 2))
                painter.drawLine(QPointF(11.0, 11.0), QPointF(x, y))

            # Custom knobs
            else:
                painter.restore()
                return

            if self.HOVER_MIN < self.fHoverStep < self.HOVER_MAX:
                self.fHoverStep += 1 if self.fIsHovered else -1
                QTimer.singleShot(20, self.update)

        else:  # isEnabled()
            target = QRectF(0.0, 0.0, self.fPixmapBaseSize,
                            self.fPixmapBaseSize)
            painter.drawPixmap(target, self.fPixmap, target)

        painter.restore()
Exemple #56
0
 def paintEvent(self, event):
     """由于是全透明背景窗口,重绘事件中绘制透明度为1的难以发现的边框,用于调整窗口大小"""
     super(FramelessWindow, self).paintEvent(event)
     painter = QPainter(self)
     painter.setPen(QPen(QColor(255, 255, 255, 1), 2 * self.Margins))
     painter.drawRect(self.rect())
Exemple #57
0
    class Digit():
        # Poverty
        # 1. show number
        # 2. possible to change certain line's color / type

        def __init__(self, loc=(0, 0)):
            self.length = 10
            self.width = 4
            self.line_gap = 1
            self.initUI(loc)
            self.num = {
                "0": [1, 1, 1, 0, 1, 1, 1],  #6
                "1": [0, 0, 1, 0, 0, 1, 0],  #2
                "2": [1, 0, 1, 1, 1, 0, 1],  #5
                "3": [1, 0, 1, 1, 0, 1, 1],  #5
                "4": [0, 1, 1, 1, 0, 1, 0],  #4
                "5": [1, 1, 0, 1, 0, 1, 1],  #5
                "6": [1, 1, 0, 1, 1, 1, 1],  #6
                "7": [1, 0, 1, 0, 0, 1, 0],  #3
                "8": [1, 1, 1, 1, 1, 1, 1],  #7
                "9": [1, 1, 1, 1, 0, 1, 1],  #6
                "None": [0, 0, 0, 0, 0, 0, 0]
            }

        def initUI(self, loc):
            """
            # number encoding order with:
            —— 1
            | 2 | 3
            —— 4
            | 5 | 6
            —— 7
            """
            def line_create():
                line = QPainter()
                line.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                line.setBrush(QBrush(Qt.white, Qt.SolidPattern))
                return line

            self.line1 = QPainter(self)
            self.line1.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line1.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line1.drawRect(loc[0] + self.line_gap + self.width, loc[1],
                                self.length, self.width)

            self.line2 = QPainter(self)
            self.line2.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line2.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line2.drawRect(loc[0], loc[1] + self.line_gap, self.width,
                                self.length)

            self.line3 = QPainter(self)
            self.line3.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line3.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line3.drawRect(
                loc[0] + 2 * self.line_gap + self.length + self.width,
                loc[1] + self.line_gap, self.width, self.length)

            self.line4 = QPainter(self)
            self.line4.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line4.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line4.drawRect(
                loc[0] + self.line_gap + self.width,
                loc[1] + 2 * self.line_gap + self.length + self.width,
                self.length, self.width)

            self.line5 = QPainter(self)
            self.line5.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line5.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line5.drawRect(
                loc[0],
                loc[1] + 3 * self.line_gap + self.length + 2 * self.width,
                self.width, self.length)

            self.line6 = QPainter(self)
            self.line6.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line6.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line6.drawRect(
                loc[0] + 2 * self.line_gap + self.length + self.width,
                loc[1] + 3 * self.line_gap + self.length + 2 * self.width,
                self.width, self.length)

            self.line7 = QPainter(self)
            self.line7.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line7.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line7.drawRect(
                loc[0] + self.line_gap + self.width,
                loc[1] + 4 * self.line_gap + 2 * self.length + 2 * self.width,
                self.length, self.width)
            self.lines = [
                self.line1, self.line2, self.line3, self.line4, self.line5,
                self.line6, self.line7
            ]
class MAIN_WINDOW(QMainWindow):
    def __init__(self):

        self.SCREEN_X = tkinter.Tk().winfo_screenwidth()
        self.SCREEN_Y = tkinter.Tk().winfo_screenheight()

        super().__init__()

        self.setWindowTitle("Order Entry")
        self.ICON = QIcon("STYLES/WINDOW_ICON_SHOPPING_CART.png")
        self.setWindowIcon(self.ICON)

        self.setGeometry(0, 0, self.SCREEN_X, self.SCREEN_Y)
        self.setStyleSheet(qss_file)

        self.show()

        self.Active_Widgets = []

        self.ORDERS = CURSOR.execute('SELECT * FROM Orders').fetchall()[-1][-1]

        self.BOOT_SCREEN()

    def paintEvent(self, paintEvent):

        self.DRAWING_TOOL = QPainter(self)
        self.DRAWING_TOOL.setBrush(QColor(147, 22, 33))
        self.DRAWING_TOOL.begin(self)
        self.DRAWING_TOOL.drawRect(0, 0, 300, self.SCREEN_Y)
        self.DRAWING_TOOL.drawRect(self.SCREEN_X - 300, 0, self.SCREEN_X,
                                   self.SCREEN_Y)
        self.DRAWING_TOOL.end()

    def BOOT_SCREEN(self):

        self.Remove_Widgets()

        self.Username = QLineEdit(self)
        self.Password = QLineEdit(self)

        self.Username_Label = QLabel(self)
        self.Password_Label = QLabel(self)

        self.Password_Label.setText("Password: "******"Username: "******"Sign in", self)

        self.Active_Widgets.append(self.BUTTON)

        self.BUTTON.setGeometry(int(self.SCREEN_X / 2 - 50),
                                int(self.SCREEN_Y / 2 + 80), 100, 40)

        self.BUTTON.clicked.connect(self.Sign_In)

        for elem in self.Active_Widgets:
            elem.setStyleSheet(qss_file)
            elem.show()

    def Order_Entry(self):

        self.Remove_Widgets()

        global sentinel
        sentinel += 1

        self.CLIENT_NAME_LABEL = QLabel(self)
        self.CLIENT_ADDRESS_LABEL = QLabel(self)
        self.CLIENT_EMAIL_LABEL = QLabel(self)
        self.PRODUCT_NAME_LABEL = QLabel(self)
        self.AMOUNT_LABEL = QLabel(self)
        self.SEARCH_DISPLAY = QTextEdit(self)

        self.CLIENT_NAME_LABEL.setText("Client name: ")
        self.CLIENT_ADDRESS_LABEL.setText("Client address: ")
        self.CLIENT_EMAIL_LABEL.setText("Email: ")
        self.PRODUCT_NAME_LABEL.setText("Product name: ")
        self.AMOUNT_LABEL.setText("Amount: ")
        self.SEARCH_DISPLAY.setReadOnly(True)

        self.CLIENT_NAME_LABEL.setGeometry(int(self.SCREEN_X / 2 - 450),
                                           int(self.SCREEN_Y / 2 - 300), 300,
                                           30)
        self.CLIENT_ADDRESS_LABEL.setGeometry(int(self.SCREEN_X / 2 - 450),
                                              int(self.SCREEN_Y / 2 - 225),
                                              300, 30)
        self.CLIENT_EMAIL_LABEL.setGeometry(int(self.SCREEN_X / 2 - 450),
                                            int(self.SCREEN_Y / 2 - 145), 300,
                                            30)
        self.PRODUCT_NAME_LABEL.setGeometry(int(self.SCREEN_X / 2 - 450),
                                            int(self.SCREEN_Y / 2 - 65), 300,
                                            30)
        self.AMOUNT_LABEL.setGeometry(int(self.SCREEN_X / 2 - 450),
                                      int(self.SCREEN_Y / 2 + 15), 300, 30)
        self.SEARCH_DISPLAY.setGeometry(int(self.SCREEN_X / 2 + 70),
                                        int(self.SCREEN_Y / 2 - 225), 400, 300)

        self.CLIENT_NAME = QLineEdit(self)
        self.CLIENT_ADDRESS = QLineEdit(self)
        self.CLIENT_EMAIL = QLineEdit(self)
        self.PRODUCT_NAME = QLineEdit(self)
        self.AMOUNT = QLineEdit(self)
        self.SEARCH_BAR = QLineEdit(self)

        self.SUBMIT = QPushButton("Submit Client's \n Order Now", self)
        self.ENTER_SEARCH = QPushButton("Search", self)
        self.HELP_BUTTON = QPushButton("About and \n Void", self)
        self.SIGN_OUT = QPushButton("Sign \n out", self)

        self.CLIENT_NAME.setGeometry(int(self.SCREEN_X / 2 - 270),
                                     int(self.SCREEN_Y / 2 - 300), 300, 30)
        self.CLIENT_ADDRESS.setGeometry(int(self.SCREEN_X / 2 - 270),
                                        int(self.SCREEN_Y / 2 - 225), 300, 30)
        self.CLIENT_EMAIL.setGeometry(int(self.SCREEN_X / 2 - 270),
                                      int(self.SCREEN_Y / 2 - 145), 300, 30)
        self.PRODUCT_NAME.setGeometry(int(self.SCREEN_X / 2 - 270),
                                      int(self.SCREEN_Y / 2 - 65), 300, 30)
        self.AMOUNT.setGeometry(int(self.SCREEN_X / 2 - 270),
                                int(self.SCREEN_Y / 2 + 15), 300, 30)
        self.SEARCH_BAR.setGeometry(int(self.SCREEN_X / 2 + 70),
                                    int(self.SCREEN_Y / 2 - 300), 300, 30)

        self.SUBMIT.setGeometry(int(self.SCREEN_X / 2 - 450),
                                int(self.SCREEN_Y / 2 + 60), 180, 60)
        self.SIGN_OUT.setGeometry(int(self.SCREEN_X / 2 - 260),
                                  int(self.SCREEN_Y / 2 + 60), 130, 60)
        self.HELP_BUTTON.setGeometry(int(self.SCREEN_X / 2 - 120),
                                     int(self.SCREEN_Y / 2 + 60), 180, 60)
        self.ENTER_SEARCH.setGeometry(int(self.SCREEN_X / 2 + 390),
                                      int(self.SCREEN_Y / 2 - 300), 100, 30)

        self.SUBMIT.clicked.connect(self.Add_Order)
        self.ENTER_SEARCH.clicked.connect(self.Order_Search)
        self.SIGN_OUT.clicked.connect(self.BOOT_SCREEN)
        self.HELP_BUTTON.clicked.connect(self.HELP_VOID)

        self.Active_Widgets.append(self.CLIENT_NAME)
        self.Active_Widgets.append(self.CLIENT_ADDRESS)
        self.Active_Widgets.append(self.AMOUNT)
        self.Active_Widgets.append(self.PRODUCT_NAME)
        self.Active_Widgets.append(self.CLIENT_EMAIL)
        self.Active_Widgets.append(self.SEARCH_BAR)

        self.Active_Widgets.append(self.CLIENT_NAME_LABEL)
        self.Active_Widgets.append(self.CLIENT_ADDRESS_LABEL)
        self.Active_Widgets.append(self.CLIENT_EMAIL_LABEL)
        self.Active_Widgets.append(self.AMOUNT_LABEL)
        self.Active_Widgets.append(self.PRODUCT_NAME_LABEL)
        self.Active_Widgets.append(self.SEARCH_DISPLAY)

        self.Active_Widgets.append(self.SUBMIT)
        self.Active_Widgets.append(self.ENTER_SEARCH)
        self.Active_Widgets.append(self.HELP_BUTTON)
        self.Active_Widgets.append(self.SIGN_OUT)

        for elem in self.Active_Widgets:
            elem.show()
            elem.setStyleSheet(qss_file)

    def HELP_VOID(self):

        self.Remove_Widgets()
        self.SUPPORT_TEXT = QTextEdit(self)
        self.SUPPORT_TEXT.setGeometry(350, 50, 900, 240)
        self.SUPPORT_TEXT.setReadOnly(True)
        self.HTML_FOR_HELP = open("STYLES/CONTACT_SHEET.html").read()
        self.SUPPORT_TEXT.setHtml(self.HTML_FOR_HELP)
        self.Active_Widgets.append(self.SUPPORT_TEXT)

        self.BACK = QPushButton("Back", self)
        self.Active_Widgets.append(self.BACK)
        self.BACK.setGeometry(350, 250, 100, 40)
        self.BACK.clicked.connect(self.Order_Entry)

        self.VOID_LABEL = QLabel(self)
        self.VOID_LABEL.setText("Void Order Number: ")
        self.VOID_LABEL.setGeometry(350, 300, 300, 40)
        self.Active_Widgets.append(self.VOID_LABEL)

        self.VOID_NUMBER = QLineEdit(self)
        self.VOID_NUMBER.setGeometry(600, 300, 300, 40)
        self.Active_Widgets.append(self.VOID_NUMBER)

        self.VOID_SUBMIT = QPushButton("Submit", self)
        self.VOID_SUBMIT.setGeometry(350, 350, 100, 40)
        self.VOID_SUBMIT.clicked.connect(self.add_voids)
        self.Active_Widgets.append(self.VOID_SUBMIT)

        for elem in self.Active_Widgets:
            elem.show()
            elem.setStyleSheet(qss_file)

    def add_voids(self):

        self.TEMP_ORDER_NUMBER = "\'" + self.VOID_NUMBER.text() + "\'"

        if self.TEMP_ORDER_NUMBER != "''" and self.TEMP_ORDER_NUMBER != "'0'":
            try:
                CURSOR.execute('DELETE FROM Orders WHERE order_number = ' +
                               self.TEMP_ORDER_NUMBER)
            except:
                print("FAILED")
            FILE.commit()

            self.VOID_NUMBER.clear()

    def Order_Search(self):

        self.SEARCH_DISPLAY.clear()

        self.TEMP_NAME_SEARCH = self.SEARCH_BAR.text()

        if len(self.TEMP_NAME_SEARCH) > 0:

            for elem in (CURSOR.execute('SELECT * FROM Orders')).fetchall():

                if elem != CURSOR.execute(
                        'SELECT * FROM Orders').fetchall()[0]:

                    if self.TEMP_NAME_SEARCH.lower() in str(elem[0]).lower():

                        self.SEARCH_DISPLAY.insertPlainText(
                            "Name: " + str(elem[0]) + "\n" + "Address: " +
                            str(elem[1]) + "\n" + "Email: " + str(elem[2]) +
                            "\n" + "Product Name: " + str(elem[3]) + "\n" +
                            "Amount: " + str(elem[4]) + "\n" +
                            "Order Number: " + str(elem[5]) + "\n" +
                            "----------" + "\n")

        else:
            for elem in (CURSOR.execute('SELECT * FROM Orders').fetchall()):

                if elem != CURSOR.execute(
                        'SELECT * FROM Orders').fetchall()[0]:

                    self.SEARCH_DISPLAY.insertPlainText(
                        "Name: " + str(elem[0]) + "\n" + "Address: " +
                        str(elem[1]) + "\n" + "Email: " + str(elem[2]) + "\n" +
                        "Product Name: " + str(elem[3]) + "\n" + "Amount: " +
                        str(elem[4]) + "\n" + "Order Number: " + str(elem[5]) +
                        "\n" + "----------" + "\n")

    def Add_Order(self):

        self.ORDERS += 1
        self.TEMP_NAME = "\'" + self.CLIENT_NAME.text() + "\'"
        self.TEMP_EMAIL = "\'" + self.CLIENT_EMAIL.text() + "\'"
        self.TEMP_ADDR = "\'" + self.CLIENT_ADDRESS.text() + "\'"
        self.TEMP_PROD = "\'" + self.PRODUCT_NAME.text() + "\'"
        self.TEMP_AMOUNT = "\'" + self.AMOUNT.text() + "\'"

        if self.TEMP_EMAIL != "''" and self.TEMP_NAME != "''" and self.TEMP_ADDR != "''" and self.TEMP_PROD != "''" and self.TEMP_AMOUNT != "''":

            CURSOR.execute('INSERT INTO Orders VALUES(' + self.TEMP_NAME +
                           ', ' + self.TEMP_ADDR + ', ' + self.TEMP_EMAIL +
                           ', ' + self.TEMP_PROD + ', ' + self.TEMP_AMOUNT +
                           ', ' + str(self.ORDERS) + ')')

            FILE.commit()

            self.CLIENT_ADDRESS.clear()
            self.PRODUCT_NAME.clear()
            self.CLIENT_EMAIL.clear()
            self.CLIENT_NAME.clear()
            self.AMOUNT.clear()

    def Sign_In(self):

        self.DATA = CURSOR.execute('SELECT * FROM Credentials')

        for elem in self.DATA.fetchall():

            if (elem[0] == self.Username.text()):

                if (elem[-1] == self.Password.text()):

                    self.Remove_Widgets()

                    self.Order_Entry()

    def Remove_Widgets(self):
        for item in self.Active_Widgets:

            item.hide()

        self.Active_Widgets = []
 def paintEvent(self, event):
     color = self.controller.get_current_color()
     painter = QPainter(self)
     painter.setBrush(QBrush(color, Qt.SolidPattern))
     painter.setPen(QPen(color))
     painter.drawRect(0, 0, self.width(), self.height())
 def paint(self, qp: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget = None):
     qp.setPen(self._pen)
     qp.drawRect(self.boundingRect())