示例#1
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)
示例#2
0
	def paintEvent(self, e):
		qp = QPainter()
		qp.begin(self)
		qp.setBrush(QColor(200, 0, 0))
		qp.drawEllipse(0,0,50,50)
		qp.setPen(QColor(0, 0, 0))
		qp.drawText(e.rect(), Qt.AlignVCenter,str(self.node.heuristicValue))
示例#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.drawLine(0, 0, width, 0)
        qp.drawLine(0, 0, 0, height)
        qp.drawLine(width, 0, width, height)
        qp.drawLine(0, height, width, height)

        #draw plot
        width  -= 1
        height -= 1 
        if len(self.data):
            qp.setPen(self.plot_color)
            max_val = max(self.data)
            points = list();
            for index in range(len(self.data)-1, 1, -1):
                points.append(QPoint((width / 100 * index),       height - (height / max_val * self.data[index])))
            points.append(QPoint(1,     height))
            points.append(QPoint(width, height))
            qp.setBrush(self.plot_color)
            qp.drawPolygon(*points)
        qp.end()
        logger.debug("paintEvent End: {0}".format(self))
示例#4
0
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

    pixmap = QPixmap(25 * 10, 25 * 10)
    pixmap.fill(backgroundColor)
    painter = QPainter()
    painter.begin(pixmap)
    pen = QPen(foregroundColor)
    painter.setPen(pen)
    painter.setRenderHint(QPainter.Antialiasing)
    font = QFont()
    font.setBold(True)
    font.setPixelSize(25 * 10 - 30)
    path = QPainterPath()
    path.addText(QPointF(50, 25 * 10 - 50), font, name)
    brush = QBrush(foregroundColor)
    painter.setBrush(brush)
    painter.drawPath(path)
    painter.setFont(font)
    painter.end()
    pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation)
    label.setPixmap(pixmap)

    spinbox = DelayedSpinBox(750)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
示例#5
0
 def paintEvent(self, e): # Событие перерисовки окна
     qp = QPainter()
     qp.begin(self)
     self.DrawLines(qp) # Отрисовка ребер
     self.drawVertex(qp) # Отрисовка вершин
     self.MoveButton(qp) # Перемещение кнопки в правый нижний угол
     qp.end()
示例#6
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))
示例#7
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))
 def __grabRegion(self):
     """
     Private method to grab the selected region (i.e. do the snapshot).
     """
     pol = QPolygon(self.__selection)
     if not pol.isEmpty():
         self.__grabbing = True
         
         xOffset = self.__pixmap.rect().x() - pol.boundingRect().x()
         yOffset = self.__pixmap.rect().y() - pol.boundingRect().y()
         translatedPol = pol.translated(xOffset, yOffset)
         
         pixmap2 = QPixmap(pol.boundingRect().size())
         pixmap2.fill(Qt.transparent)
         
         pt = QPainter()
         pt.begin(pixmap2)
         if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff):
             pt.setRenderHints(
                 QPainter.Antialiasing |
                 QPainter.HighQualityAntialiasing |
                 QPainter.SmoothPixmapTransform,
                 True)
             pt.setBrush(Qt.black)
             pt.setPen(QPen(QBrush(Qt.black), 0.5))
             pt.drawPolygon(translatedPol)
             pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
         else:
             pt.setClipRegion(QRegion(translatedPol))
             pt.setCompositionMode(QPainter.CompositionMode_Source)
         
         pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect())
         pt.end()
         
         self.grabbed.emit(pixmap2)
示例#9
0
 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()
def drawIndicatorIcon(palette, style):
    pix = QPixmap(14, 14)
    pix.fill(Qt.transparent)
    branchOption = QStyleOption()
    #r = QRect(QPoint(0, 0), pix.size())
    branchOption.rect = QRect(2, 2, 9, 9) ## ### hardcoded in qcommonstyle.cpp
    branchOption.palette = palette
    branchOption.state = QStyle.State_Children

    p = QPainter()
    ## Draw closed state
    p.begin(pix)
    style.drawPrimitive(QStyle.PE_IndicatorBranch, branchOption, p)
    p.end()
    rc = QIcon(pix)
    rc.addPixmap(pix, QIcon.Selected, QIcon.Off)
    ## Draw opened state
    branchOption.state |= QStyle.State_Open
    pix.fill(Qt.transparent)
    p.begin(pix)
    style.drawPrimitive(QStyle.PE_IndicatorBranch, branchOption, p)
    p.end()

    rc.addPixmap(pix, QIcon.Normal, QIcon.On)
    rc.addPixmap(pix, QIcon.Selected, QIcon.On)
    return rc
	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()
    def paintEvent(self, e):
        print("Paint event")

        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()
示例#13
0
    def paintEvent(self, event):

        background = QRadialGradient(QPointF(self.rect().topLeft()), 500,
                QPointF(self.rect().bottomRight()))
        background.setColorAt(0, self.backgroundColor1)
        background.setColorAt(1, self.backgroundColor2)

        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(event.rect(), QBrush(background))

        painter.setPen(self.pen)

        for bubble in self.bubbles:

            if QRectF(bubble.position - QPointF(bubble.radius, bubble.radius),
                      QSizeF(2*bubble.radius, 2*bubble.radius)).intersects(QRectF(event.rect())):
                bubble.drawBubble(painter)

        if self.newBubble:

            self.newBubble.drawBubble(painter)

        painter.end()
示例#14
0
    def mousePressEvent(self, event):
        child = self.childAt(event.pos())
        if not child:
            return

        pixmap = QPixmap(child.pixmap())

        itemData = QByteArray()
        dataStream = QDataStream(itemData, QIODevice.WriteOnly)
        dataStream << pixmap << QPoint(event.pos() - child.pos())

        mimeData = QMimeData()
        mimeData.setData('application/x-dnditemdata', itemData)

        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - child.pos())

        tempPixmap = QPixmap(pixmap)
        painter = QPainter()
        painter.begin(tempPixmap)
        painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127))
        painter.end()

        child.setPixmap(tempPixmap)

        if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
            child.close()
        else:
            child.show()
            child.setPixmap(pixmap)
示例#15
0
文件: main.py 项目: Xevaquor/aipac
    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()
示例#16
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QFontMetrics(self.font())
        size = metric.size(Qt.TextSingleLine, text)

        image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(0, 0, 0, 0))

        font = QFont()
        font.setStyleStrategy(QFont.ForceOutline)

        painter = QPainter()
        painter.begin(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QPixmap.fromImage(image))
        self.labelText = text
示例#17
0
 def updateFilledCircle(self, s):
     size = s * self.zoom
     pixmap = QPixmap(self.width(), self.height())
     pixmap.fill(Qt.transparent)
     #painter filled ellipse
     p = QPalette()
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     brush = QBrush(p.link().color())
     painter.setBrush(brush)
     painter.setOpacity(0.4)
     painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter.end()
     #painter ellipse 2
     painter2 = QPainter()
     painter2.begin(pixmap)
     painter2.setRenderHint(QPainter.Antialiasing)
     pen2 = QPen(Qt.green)
     pen2.setWidth(1)
     painter2.setPen(pen2)
     painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter2.end()
     
     self.ellipseLabel.setPixmap(QPixmap(pixmap))
     self.lastSize = s
示例#18
0
    def nextFrame(self):
        mouse_pos = self.mapFromGlobal(QCursor.pos())
        mouse_x = mouse_pos.x()
        mouse_y = mouse_pos.y()

        self.x1 = mouse_x
        self.y1 = mouse_y
        self.radius1 = self.radius1 + math.sin(self.frame_count / 8) * 4

        delay = 20
        self.x2 += (mouse_x - self.x2) / delay
        self.y2 += (mouse_y - self.y2) / delay

        self.frame_count += 1

        if self.paint_image.width() != self.width() or self.paint_image.height() != self.height():
            self.paint_image = QPixmap(self.width(), self.height())
            self.paint_image.fill(self.background_color)

        p = QPainter()
        p.begin(self.paint_image) # auf das paint_image malen
        p.setBackground(self.background_color) # color when stuff is erased

        # Hintergrund löschen, wenn Rechteck bei der Maus angekommen ist
        # print("{0}, {1}".format(self.x2, mouse_x))
        if round(self.x2) == mouse_x and round(self.y2) == mouse_y:
            p.eraseRect(0, 0, self.paint_image.width(), self.paint_image.height())

        self.drawFrame(p)
        p.end()
        self.repaint()
示例#19
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
示例#20
0
 def paintEvent(self, e):
   
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHints(QPainter.Antialiasing, True)
     self.doDrawing(qp)        
     qp.end()
示例#21
0
    def make_cypherseed(self, img, rawnoise, calibration=False, is_seed = True):
        img = img.convertToFormat(QImage.Format_Mono)
        p = QPainter()
        p.begin(img)
        p.setCompositionMode(26) #xor
        p.drawImage(0, 0, rawnoise)
        p.end()
        cypherseed = self.pixelcode_2x2(img)
        cypherseed = QBitmap.fromImage(cypherseed)
        cypherseed = cypherseed.scaled(self.f_size, Qt.KeepAspectRatio)
        cypherseed = self.overlay_marks(cypherseed, True, calibration)

        if not is_seed:
            self.filename_prefix = 'custom_secret_'
            self.was = _('Custom secret')
        else:
            self.filename_prefix = self.wallet_name + '_seed_'
            self.was = self.wallet_name + ' ' + _('seed')
            if self.extension:
                self.ext_warning(self.c_dialog)


        if not calibration:
            self.toPdf(QImage(cypherseed))
            QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
            cypherseed.save(self.get_path_to_revealer_file('.png'))
            self.bcrypt(self.c_dialog)
        return cypherseed
示例#22
0
    def calibration_pdf(self, image):
        printer = QPrinter()
        printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
        printer.setResolution(600)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(self.get_path_to_calibration_file())
        printer.setPageMargins(0,0,0,0,6)

        painter = QPainter()
        painter.begin(printer)
        painter.drawImage(553,533, image)
        font = QFont('Source Sans Pro', 10, QFont.Bold)
        painter.setFont(font)
        painter.drawText(254,277, _("Calibration sheet"))
        font = QFont('Source Sans Pro', 7, QFont.Bold)
        painter.setFont(font)
        painter.drawText(600,2077, _("Instructions:"))
        font = QFont('Source Sans Pro', 7, QFont.Normal)
        painter.setFont(font)
        painter.drawText(700, 2177, _("1. Place this paper on a flat and well iluminated surface."))
        painter.drawText(700, 2277, _("2. Align your Revealer borderlines to the dashed lines on the top and left."))
        painter.drawText(700, 2377, _("3. Press slightly the Revealer against the paper and read the numbers that best "
                                      "match on the opposite sides. "))
        painter.drawText(700, 2477, _("4. Type the numbers in the software"))
        painter.end()
示例#23
0
    def setNameAndBrush(self, sigma, color=Qt.black):
        self.sigma = sigma
        self.setText(f'σ{self.column}'.translate(self.sub_trans))
        if self.sigma is not None:
            total_window = (1 + 2 * int(self.sigma * self.window_size + 0.5))
            self.setToolTip(f'sigma = {sigma:.1f} pixels, window diameter = {total_window:.1f}')
        font = QFont()
        font.setPointSize(10)
        # font.setBold(True)
        self.setFont(font)
        self.setForeground(color)

        pixmap = QPixmap(self.pixmapSize)
        pixmap.fill(Qt.transparent)
        painter = QPainter()
        painter.begin(pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(color)
        brush = QBrush(color)
        painter.setBrush(brush)
        painter.drawEllipse(QRect(old_div(self.pixmapSize.width(), 2) - old_div(self.brushSize, 2),
                                  old_div(self.pixmapSize.height(), 2) - old_div(self.brushSize, 2),
                                  self.brushSize, self.brushSize))
        painter.end()
        self.setIcon(QIcon(pixmap))
        self.setTextAlignment(Qt.AlignVCenter)
示例#24
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()
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)       
     
     getWorld().draw(painter)            
     
     painter.end()      
示例#26
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 127)))
        painter.setPen(QPen(Qt.NoPen))

        for i in range(6):
            x_pos = self.width() / 2 + 30 * \
                math.cos(2 * math.pi * i / 6.0) - 10
            y_pos = self.height() / 2 + 30 * \
                math.sin(2 * math.pi * i / 6.0) - 10
            if (self.counter / 5) % 6 == i:
                linear_gradient = QLinearGradient(
                    x_pos + 10, x_pos, y_pos + 10, y_pos)
                linear_gradient.setColorAt(0, QColor(135, 206, 250))
                linear_gradient.setColorAt(1, QColor(0, 0, 128))
                painter.setBrush(QBrush(linear_gradient))
            else:
                linear_gradient = QLinearGradient(
                    x_pos - 10, x_pos, y_pos + 10, y_pos)
                linear_gradient.setColorAt(0, QColor(105, 105, 105))
                linear_gradient.setColorAt(1, QColor(0, 0, 0))
                painter.setBrush(QBrush(linear_gradient))
            painter.drawEllipse(
                x_pos,
                y_pos,
                20, 20)

        painter.end()
示例#27
0
 def updateCircle(self, s):
     size = s * self.zoom
     pixmap = QPixmap(self.width(), self.height())
     pixmap.fill(Qt.transparent)
     #painter ellipse 1
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     pen = QPen(Qt.red)
     pen.setWidth(3)
     painter.setPen(pen)
     brush = QBrush(Qt.green)
     painter.setBrush(brush)
     painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter.end()
     #painter ellipse 2
     painter2 = QPainter()
     painter2.begin(pixmap)
     painter2.setRenderHint(QPainter.Antialiasing)
     pen2 = QPen(Qt.green)
     pen2.setStyle(Qt.DotLine)
     pen2.setWidth(3)
     painter2.setPen(pen2)
     painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter2.end()
     
     self.ellipseLabel.setPixmap(QPixmap(pixmap))
     self.lastSize = s
示例#28
0
 def paintEvent(self, event):
     logger.debug("paintEvent: {0} - {1}".format(self, event.rect()))
     qp = QPainter()
     qp.begin(self)
     self.drawBackground(event, qp)
     qp.end()
     logger.debug("paintEvent End: " + str(self))
示例#29
0
    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)

        self.drawWidget(qp)
        qp.end()
        super().paintEvent(e)
示例#30
0
    def paintEvent(self, event):
        """Qt method override to paint a custom image on the Widget."""
        super(FigureCanvas, self).paintEvent(event)

        qp = QPainter()
        qp.begin(self)

        # Prepare paint rect :

        fw = self.frameWidth()
        rect = QRect(0 + fw, 0 + fw,
                     self.size().width() - 2 * fw,
                     self.size().height() - 2 * fw)

        # Check/update image buffer :

        qpix2print = None
        for qpix in self.qpix_buff:
            if qpix.size().width() == rect.width():
                qpix2print = qpix
                break

        if qpix2print is None:
            qpix2print = self.img.scaledToWidth(
                rect.width(), mode=Qt.SmoothTransformation)
            self.qpix_buff.append(qpix2print)

        # Draw pixmap :

#        qp.setRenderHint(QPainter.Antialiasing, True)
        qp.drawPixmap(rect, qpix2print)

        qp.end()
示例#31
0
文件: HUD.py 项目: wangyeee/MiniGCS
    def paintEvent(self, event):
        unused(event)
        if self.isVisible():

            # Read out most important values to limit hash table lookups
            # Low-pass roll, pitch and yaw
            self.rollLP = self.roll#rollLP * 0.2f + 0.8f * roll
            self.pitchLP = self.pitch#pitchLP * 0.2f + 0.8f * pitch
            self.yawLP = self.yaw if isinf(self.yaw) == False and isnan(self.yaw) == False else self.yawLP#yawLP * 0.2f + 0.8f * yaw

            # Translate for yaw
            maxYawTrans = 60.0

            newYawDiff = self.yawDiff
            if isinf(newYawDiff):
                newYawDiff = self.yawDiff
            if newYawDiff > M_PI:
                newYawDiff = newYawDiff - M_PI

            if newYawDiff < -M_PI:
                newYawDiff = newYawDiff + M_PI

            newYawDiff = self.yawDiff * 0.8 + newYawDiff * 0.2

            self.yawDiff = newYawDiff

            self.yawInt += newYawDiff

            if self.yawInt > M_PI:
                self.yawInt = M_PI
            if self.yawInt < -M_PI:
                self.yawInt = -M_PI

            yawTrans = self.yawInt * maxYawTrans
            self.yawInt *= 0.6

            if (yawTrans < 5.0) and (yawTrans > -5.0):
                yawTrans = 0

            # Negate to correct direction
            yawTrans = -yawTrans
            yawTrans = 0
            #qDebug() << "yaw translation" << yawTrans << "integral" << yawInt << "difference" << yawDiff << "yaw" << yaw

            # And if either video or the data stream is enabled, draw the next frame.
            if self.videoEnabled:
                self.xImageFactor = self.width() / float(self.glImage.width())
                self.yImageFactor = self.height() / float(self.glImage.height())

            painter = QPainter()
            painter.begin(self)
            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
            pmap = QPixmap.fromImage(self.glImage).scaledToWidth(self.width())
            painter.drawPixmap(0, (self.height() - pmap.height()) / 2, pmap)

            # END OF OPENGL PAINTING

            if self.HUDInstrumentsEnabled:
                #glEnable(GL_MULTISAMPLE)
                # QT PAINTING
                #makeCurrent()

                painter.translate((self.vwidth/2.0+self.xCenterOffset)*self.scalingFactor, (self.vheight/2.0+self.yCenterOffset)*self.scalingFactor)
                # COORDINATE FRAME IS NOW (0,0) at CENTER OF WIDGET
                # Draw all fixed indicators
                # BATTERY
                self.paintText(self.fuelStatus, self.fuelColor, 6.0, (-self.vwidth/2.0) + 10, -self.vheight/2.0 + 6, painter)
                # Waypoint
                self.paintText(self.waypointName, self.defaultColor, 6.0, (-self.vwidth/3.0) + 10, +self.vheight/3.0 + 15, painter)

                linePen = QPen(Qt.SolidLine)
                linePen.setWidth(self.refLineWidthToPen(1.0))
                linePen.setColor(self.defaultColor)
                painter.setBrush(Qt.NoBrush)
                painter.setPen(linePen)

                # YAW INDICATOR
                #
                #      .
                #    .   .
                #   .......
                #
                _yawIndicatorWidth = 12.0
                _yawIndicatorY = self.vheight/2.0 - 15.0
                yawIndicator = QPolygon(4)
                yawIndicator.setPoint(0, QPoint(self.refToScreenX(0.0), self.refToScreenY(_yawIndicatorY)))
                yawIndicator.setPoint(1, QPoint(self.refToScreenX(_yawIndicatorWidth/2.0), self.refToScreenY(_yawIndicatorY+_yawIndicatorWidth)))
                yawIndicator.setPoint(2, QPoint(self.refToScreenX(-_yawIndicatorWidth/2.0), self.refToScreenY(_yawIndicatorY+_yawIndicatorWidth)))
                yawIndicator.setPoint(3, QPoint(self.refToScreenX(0.0), self.refToScreenY(_yawIndicatorY)))
                painter.drawPolyline(yawIndicator)
                painter.setPen(linePen)
                # CENTER

                # HEADING INDICATOR
                #
                #    __      __
                #       \/\/
                #
                _hIndicatorWidth = 20.0
                _hIndicatorY = -25.0
                _hIndicatorYLow = _hIndicatorY + _hIndicatorWidth / 6.0
                _hIndicatorSegmentWidth = _hIndicatorWidth / 7.0
                hIndicator = QPolygon(7)
                hIndicator.setPoint(0, QPoint(self.refToScreenX(0.0-_hIndicatorWidth/2.0), self.refToScreenY(_hIndicatorY)))
                hIndicator.setPoint(1, QPoint(self.refToScreenX(0.0-_hIndicatorWidth/2.0+_hIndicatorSegmentWidth*1.75), self.refToScreenY(_hIndicatorY)))
                hIndicator.setPoint(2, QPoint(self.refToScreenX(0.0-_hIndicatorSegmentWidth*1.0), self.refToScreenY(_hIndicatorYLow)))
                hIndicator.setPoint(3, QPoint(self.refToScreenX(0.0), self.refToScreenY(_hIndicatorY)))
                hIndicator.setPoint(4, QPoint(self.refToScreenX(0.0+_hIndicatorSegmentWidth*1.0), self.refToScreenY(_hIndicatorYLow)))
                hIndicator.setPoint(5, QPoint(self.refToScreenX(0.0+_hIndicatorWidth/2.0-_hIndicatorSegmentWidth*1.75), self.refToScreenY(_hIndicatorY)))
                hIndicator.setPoint(6, QPoint(self.refToScreenX(0.0+_hIndicatorWidth/2.0), self.refToScreenY(_hIndicatorY)))
                painter.drawPolyline(hIndicator)

                # SETPOINT
                _centerWidth = 8.0
                painter.drawEllipse(
                    QPointF(self.refToScreenX(min(10.0, self.desiredRoll * 10.0)),
                            self.refToScreenY(min(10.0, self.desiredPitch * 10.0))),
                    self.refToScreenX(_centerWidth/2.0), self.refToScreenX(_centerWidth/2.0))

                _centerCrossWidth = 20.0
                # left
                painter.drawLine(QPointF(self.refToScreenX(-_centerWidth / 2.0), self.refToScreenY(0.0)),
                                 QPointF(self.refToScreenX(-_centerCrossWidth / 2.0), self.refToScreenY(0.0)))
                # right
                painter.drawLine(QPointF(self.refToScreenX(_centerWidth / 2.0), self.refToScreenY(0.0)),
                                 QPointF(self.refToScreenX(_centerCrossWidth / 2.0), self.refToScreenY(0.0)))
                # top
                painter.drawLine(QPointF(self.refToScreenX(0.0), self.refToScreenY(-_centerWidth / 2.0)),
                                 QPointF(self.refToScreenX(0.0), self.refToScreenY(-_centerCrossWidth / 2.0)))

                # COMPASS
                _compassY = -self.vheight/2.0 + 6.0
                compassRect = QRectF(QPointF(self.refToScreenX(-12.0), self.refToScreenY(_compassY)),
                                     QSizeF(self.refToScreenX(24.0), self.refToScreenY(12.0)))
                painter.setBrush(Qt.NoBrush)
                painter.setPen(linePen)
                painter.drawRoundedRect(compassRect, 3, 3)

                # YAW is in compass-human readable format, so 0 .. 360 deg.
                _yawDeg = (self.yawLP / M_PI) * 180.0
                if _yawDeg < 0:
                    _yawDeg += 360
                if _yawDeg > 360:
                    _yawDeg -= 360
                # final safeguard for really stupid systems
                _yawAngle = '{:3d}'.format(int(_yawDeg) % 360)
                self.paintText(_yawAngle, self.defaultColor, 8.5, -9.8, _compassY + 1.7, painter)

                painter.setBrush(Qt.NoBrush)
                painter.setPen(linePen)

                # CHANGE RATE STRIPS
                self.drawChangeRateStrip(-95.0, -60.0, 40.0, -10.0, 10.0, self.zSpeed, painter)

                # CHANGE RATE STRIPS
                self.drawChangeRateStrip(95.0, -60.0, 40.0, -10.0, 10.0, self.totalAcc, painter,True)

                # GAUGES

                # Left altitude gauge
                _gaugeAltitude = self.alt if self.alt != 0 else -self.zPos

                painter.setBrush(Qt.NoBrush)
                painter.setPen(linePen)

                self.drawChangeIndicatorGauge(-self.vGaugeSpacing, 35.0, 15.0, 10.0, _gaugeAltitude, self.defaultColor, painter, False)
                self.paintText('alt m', self.defaultColor, 5.5, -73.0, 50, painter)

                # Right speed gauge
                self.drawChangeIndicatorGauge(self.vGaugeSpacing, 35.0, 15.0, 10.0, self.totalSpeed, self.defaultColor, painter, False)
                self.paintText('v m/s', self.defaultColor, 5.5, 55.0, 50, painter)

                # Waypoint name
                if self.waypointName != '':
                    self.paintText(self.waypointName, self.defaultColor, 2.0, (-self.vwidth/3.0) + 10, +self.vheight/3.0 + 15, painter)

                # MOVING PARTS
                painter.translate(self.refToScreenX(yawTrans), 0)
                attColor = painter.pen().color()

                # Draw multi-component attitude
                for key in self.attitudes:
                    att = self.attitudes[key]
                    attColor = attColor.darker(200)
                    painter.setPen(attColor)
                    # Rotate view and draw all roll-dependent indicators
                    painter.rotate((att.x()/M_PI)* -180.0)
                    painter.translate(0, (-att.y()/M_PI)* -180.0 * self.refToScreenY(1.8))
                    #qDebug() << "ROLL" << roll << "PITCH" << pitch << "YAW DIFF" << valuesDot.value("roll", 0.0)
                    # PITCH
                    self.paintPitchLines(att.y(), painter)
                    painter.translate(0, -(-att.y()/M_PI)* -180.0 * self.refToScreenY(1.8))
                    painter.rotate(-(att.x()/M_PI)* -180.0)
            painter.end()
示例#32
0
    def createCurveIcons(self):
        pix = QPixmap(self.m_iconSize)
        painter = QPainter()

        gradient = QLinearGradient(0, 0, 0, self.m_iconSize.height())
        gradient.setColorAt(0.0, QColor(240, 240, 240))
        gradient.setColorAt(1.0, QColor(224, 224, 224))

        brush = QBrush(gradient)

        # The original C++ code uses undocumented calls to get the names of the
        # different curve types.  We do the Python equivalant (but without
        # cheating).
        curve_types = [
            (n, c) for n, c in QEasingCurve.__dict__.items()
            if isinstance(c, QEasingCurve.Type) and c != QEasingCurve.Custom
        ]
        curve_types.sort(key=lambda ct: ct[1])

        painter.begin(pix)

        for curve_name, curve_type in curve_types:
            painter.fillRect(QRect(QPoint(0, 0), self.m_iconSize), brush)

            curve = QEasingCurve(curve_type)

            if curve_type == QEasingCurve.BezierSpline:
                curve.addCubicBezierSegment(QPointF(0.4,
                                                    0.1), QPointF(0.6, 0.9),
                                            QPointF(1.0, 1.0))
            elif curve_type == QEasingCurve.TCBSpline:
                curve.addTCBSegment(QPointF(0.0, 0.0), 0, 0, 0)
                curve.addTCBSegment(QPointF(0.3, 0.4), 0.2, 1, -0.2)
                curve.addTCBSegment(QPointF(0.7, 0.6), -0.2, 1, 0.2)
                curve.addTCBSegment(QPointF(1.0, 1.0), 0, 0, 0)

            painter.setPen(QColor(0, 0, 255, 64))
            xAxis = self.m_iconSize.height() / 1.5
            yAxis = self.m_iconSize.width() / 3.0
            painter.drawLine(0, xAxis, self.m_iconSize.width(), xAxis)
            painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height())

            curveScale = self.m_iconSize.height() / 2.0

            painter.setPen(Qt.NoPen)

            # Start point.
            painter.setBrush(Qt.red)
            start = QPoint(yAxis,
                           xAxis - curveScale * curve.valueForProgress(0))
            painter.drawRect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(Qt.blue)
            end = QPoint(yAxis + curveScale,
                         xAxis - curveScale * curve.valueForProgress(1))
            painter.drawRect(end.x() - 1, end.y() - 1, 3, 3)

            curvePath = QPainterPath()
            curvePath.moveTo(QPointF(start))
            t = 0.0
            while t <= 1.0:
                to = QPointF(yAxis + curveScale * t,
                             xAxis - curveScale * curve.valueForProgress(t))
                curvePath.lineTo(to)
                t += 1.0 / curveScale

            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.strokePath(curvePath, QColor(32, 32, 32))
            painter.setRenderHint(QPainter.Antialiasing, False)

            item = QListWidgetItem()
            item.setIcon(QIcon(pix))
            item.setText(curve_name)
            self.m_ui.easingCurvePicker.addItem(item)

        painter.end()
    def save(self, filename: str, do_crop: bool=False):
        """Save a RenderIrea as one image on disk.
        
        Arguments:
            filename {str} -- The filename of the new image.
        """
        if not self.images:
            return

        # new label size
        dst_w = 0
        dst_h = 0

        # Zoom
        zoom = self.zoom()

        # Current number of images into the stack.
        nbimg = len(self.images)

        # Find the current size of the output image.
        images = []
        for i in range(0, nbimg):
            image = self.images[i]

            _w = image.width() * zoom
            _h = image.height() * zoom

            if _w > dst_w:
                dst_w = _w
            
            if _h > dst_h: 
                dst_h = _h

            # Scale now
            images.append(
                image.scaled(
                _w, _h,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            ))

        # Output image
        # ARGB since we can have all types of images (colors/grayscale/alpha channel)
        dst = QImage(dst_w, dst_h, QImage.Format_ARGB32)
        dst.fill(0) # black pixels everywhere

        # Init QPainter.
        painter = QPainter()
        painter.begin(dst) # Begin to draw inside the `dst` Image

        # Draw every stacked images.
        # From the bottom of the stack to the top.
        for i in range(0, nbimg):
            # Opacity
            painter.setOpacity(self.opacities[i])
            painter.drawImage(
                self.xx[i] * zoom,
                self.yy[i] * zoom,
                images[i]
            )

        painter.end()

        # Crop or not to crop?
        if do_crop and self.draw_rect:
            rect = QRect(self.l_pos, self.r_pos)
            dst = dst.copy(rect)

        # Save image, max quality
        dst.save(filename, None, 100)
示例#34
0
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     self.drawLines(qp)
     qp.end()
示例#35
0
文件: ui.py 项目: dturecek/dicewars
class Battle(QWidget):
    """Widget for displaying battle results
    """
    def __init__(self, game):
        super(Battle, self).__init__()
        self.game = game

        self.color = QColor(0, 0, 0)
        self.qp = QPainter()
        self.font = QFont('Helvetica', 12)
        self.pen = QPen()
        self.pen.setWidth(2)

    def paintEvent(self, event):
        self.qp.begin(self)
        self.draw_battle(event)
        self.qp.end()

    def draw_battle(self, event):
        """Draw battle results
        """
        rect = event.rect()
        label_rect = QRectF(rect.x(), rect.y(), rect.width(), 25)

        self.qp.setPen(self.color)
        self.qp.setFont(self.font)
        self.qp.drawText(label_rect, Qt.AlignCenter, 'Battle')

        if self.game.battle:
            size = rect.width() // 4

            attacker = QRectF(rect.x() + size, 30 + rect.y(), size - 10,
                              size - 10)
            defender = QRectF(rect.x() + 2 * size, 30 + rect.y(), size - 10,
                              size - 10)

            self.qp.setPen(self.color)
            self.qp.setFont(self.font)

            self.qp.setBrush(
                QColor(*player_color(self.game.battle['atk_name'])))
            self.qp.drawRect(attacker)
            self.qp.drawText(attacker, Qt.AlignCenter,
                             str(self.game.battle['atk_dice']))

            self.qp.setBrush(
                QColor(*player_color(self.game.battle['def_name'])))
            self.qp.drawRect(defender)
            self.qp.drawText(defender, Qt.AlignCenter,
                             str(self.game.battle['def_dice']))
            self.game.battle = False

        else:
            size = rect.width() // 4
            self.qp.setBrush(QColor(230, 230, 230))

            attacker = QRectF(rect.x() + size, 30 + rect.y(), size - 10,
                              size - 10)
            deffender = QRectF(rect.x() + 2 * size, 30 + rect.y(), size - 10,
                               size - 10)

            self.qp.drawRect(attacker)
            self.qp.drawRect(deffender)
示例#36
0
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHint(QPainter.Antialiasing)
     qp.drawPath(self.path)
     qp.end()
示例#37
0
    def seed_img(self, is_seed=True):

        if is_seed:
            try:
                cseed = self.get_seed()
            except UserCancelled:
                return
            except InvalidPassword as e:
                self.d.show_error(str(e))
                return
            if not cseed:
                self.d.show_message(_("This wallet has no seed"))
                return
            txt = cseed.upper()
        else:
            txt = self.txt.upper()

        img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
        bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
        bitmap.fill(Qt.white)
        painter = QPainter()
        painter.begin(bitmap)
        QFontDatabase.addApplicationFont(
            os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf'))
        if len(txt) < 102:
            fontsize = 15
            linespace = 15
            max_letters = 17
            max_lines = 6
            max_words = 3
        else:
            fontsize = 12
            linespace = 10
            max_letters = 21
            max_lines = 9
            max_words = int(max_letters / 4)

        font = QFont('Source Sans Pro', fontsize, QFont.Bold)
        font.setLetterSpacing(QFont.PercentageSpacing, 100)
        font.setPixelSize(fontsize)
        painter.setFont(font)
        seed_array = txt.split(' ')

        for n in range(max_lines):
            nwords = max_words
            temp_seed = seed_array[:nwords]
            while len(' '.join(map(str, temp_seed))) > max_letters:
                nwords = nwords - 1
                temp_seed = seed_array[:nwords]
            painter.drawText(
                QRect(0, linespace * n, self.SIZE[0], self.SIZE[1]),
                Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
            del seed_array[:nwords]

        painter.end()
        img = bitmap.toImage()
        if (self.rawnoise == False):
            self.make_rawnoise()

        self.make_cypherseed(img, self.rawnoise, False, is_seed)
        return img
示例#38
0
class Image(QLabel):
    classifiedMLP = pyqtSignal(int)
    classifiedCNN = pyqtSignal(int)
    clear = pyqtSignal()

    def __init__(self, *args):
        super().__init__(*args)
        self.pressed = False
        self.setFixedSize(200, 200)
        self.setStyleSheet('border: 3px solid grey;')

        self.classifyTimer = QTimer()
        self.classifyTimer.timeout.connect(self.classify)

        # загрузка весов нейронной сети MLP
        data = scipy.io.loadmat('weights.mat')
        self.Theta1 = np.matrix(data['Theta1'])
        self.Theta2 = np.matrix(data['Theta2'])

        # инициализация модели CNN
        jsonFile = open('model.json', 'r')
        loadedModelJson = jsonFile.read()
        jsonFile.close()
        self.cnnModel = model_from_json(loadedModelJson)
        self.cnnModel.load_weights('model.h5')
        self.cnnModel.compile(loss="categorical_crossentropy",
                              optimizer=Adam(),
                              metrics=["accuracy"])

    def mousePressEvent(self, event):
        self.pressed = True
        self.xPrev = event.x()
        self.yPrev = event.y()

        self.painter = QPainter(self.pixmap())
        self.painter.setRenderHint(QPainter.Antialiasing)
        self.painter.begin(self.pixmap())

    def mouseMoveEvent(self, event):
        if self.pressed:
            color = QColor(0, 0, 0)
            self.painter.setBrush(color)
            pen = QPen(color, 15)
            pen.setCapStyle(QtCore.Qt.RoundCap)
            self.painter.setPen(pen)

            self.painter.drawLine(self.xPrev, self.yPrev, event.x(), event.y())

            self.xPrev = event.x()
            self.yPrev = event.y()
            self.repaint()

    def mouseReleaseEvent(self, event):
        self.pressed = False
        self.painter.end()

        # запуск кода классификации картинки
        self.classifyTimer.start(1000)
        QTimer.singleShot(2000, self.clearImage)

    def classify(self):
        self.classifyTimer.stop()

        # предсказание с помощью MLP
        self.classifiedMLP.emit(self.classifyMLP())

        # предсказание с помощью свёрточной сети Keras
        self.classifiedCNN.emit(self.classifyCNN())

    def classifyMLP(self):
        # подготовка картинки к классификации
        small = self.pixmap().toImage().scaled(20, 20).convertToFormat(
            QImage.Format_Grayscale8)
        s = small.bits().asstring(20 * 20)
        sample = np.fromstring(s, dtype=np.uint8)
        sample = sample.reshape((20, 20)).T.reshape((1, 400))
        sample = (255 - sample) / 243.0

        # предсказание с помощью классификатора
        return predict(self.Theta1, self.Theta2, sample)[0] % 10

    def classifyCNN(self):
        # подготовка картинки к классификации
        small = self.pixmap().toImage().scaled(28, 28).convertToFormat(
            QImage.Format_Grayscale8)
        s = small.bits().asstring(28 * 28)
        sample = np.fromstring(s, dtype=np.uint8)
        sample = (255 - sample) / 255
        sample = sample.reshape((1, 1, 28, 28))

        # предсказание с помощью классификатора
        return np.argmax(self.cnnModel.predict(sample))


    def clearImage(self):
        self.painter.begin(self.pixmap())
        self.painter.eraseRect(self.rect())
        self.painter.end()
        self.repaint()
        self.clear.emit()
示例#39
0
 def paintEvent(self, e):
     lb = QPainter()
     lb.begin(self)
     self.drawRect(lb)
     lb.end()
示例#40
0
文件: menu.py 项目: NameOff/PyChess
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     qp.drawImage(0, 0, QImage('images/background.jpg'))
     qp.end()
示例#41
0
    def paintEvent(self, event):
        if not self._image3c.img_data:
            self._loading_bar.hide()
            self._ico_label.hide()
            self._tip_label.show()
            self.overlabel_display.hide()

            painter = QPainter()
            painter.begin(self)
            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.setRenderHint(QPainter.TextAntialiasing, True)
            painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

            painter.setPen(QPen(Qt.black, Qt.PenStyle(Qt.DashLine), 3))
            painter.setBrush(Qt.white)
            self._tip_box = (self.width() * 0.2, self.height() * 0.2,
                             self.width() * 0.6, self.height() * 0.6)
            radius = min(self.width() * 0.1, self.height() * 0.1)
            painter.drawRoundedRect(*self._tip_box, radius, radius)

            painter.end()

            self._tip_label.setGeometry(QRect(*self._tip_box))

            self._tip_label.setText(self._action_descs[0])
            self._tip_label.setAlignment(Qt.AlignCenter)

        elif self._args.sys_category * 10 + self._args.sys_channel not in self._categories:
            self._loading_bar.show()
            self._ico_label.show()
            self._tip_label.show()
            self.overlabel_display.hide()

            bar_wid = self.width() * 0.8
            bar_hig = self.height() * 0.1

            self._loading_bar.setGeometry((self.width() - bar_wid) / 2,
                                          self.height() - bar_hig * 1.2,
                                          bar_wid, bar_hig)

            resized_img = self._ico.scaled(self.width() * 0.8,
                                           self.height() * 0.8,
                                           Qt.KeepAspectRatio)
            img_wid = resized_img.size().width()
            img_hig = resized_img.size().height()

            self._ico_label.setPixmap(QPixmap.fromImage(resized_img))
            self._ico_label.setGeometry((self.width() - img_wid) / 2,
                                        bar_hig * 0.2, img_wid, img_hig)

            self._tip_label.setGeometry((self.width() - bar_wid) / 2,
                                        self.height() - bar_hig * 2.2, bar_wid,
                                        bar_hig)

        else:
            self._loading_bar.hide()
            self._ico_label.hide()
            self._tip_label.hide()
            self.overlabel_display.show()

            if not self._image3c.display:
                self._image3c.load_image(self._args.sys_category,
                                         self._args.sys_channel)
                self._resizing_image = True

            if self._image3c.display:
                if not self._move_pos:
                    self.home()

                self._move_pos[0] = self.width() - 2 if self._move_pos[
                    0] > self.width() - 2 else self._move_pos[0]
                self._move_pos[0] = 2 - self._move_pos[2] if self._move_pos[
                    0] < 2 - self._move_pos[2] else self._move_pos[0]
                self._move_pos[1] = self.height() - 2 if self._move_pos[
                    1] > self.height() - 2 else self._move_pos[1]
                self._move_pos[1] = 2 - self._move_pos[3] if self._move_pos[
                    1] < 2 - self._move_pos[3] else self._move_pos[1]

                # aspect ratio mode: IgnoreAspectRatio, KeepAspectRatio and KeepAspectRatioByExpanding.
                if self._resizing_image:
                    resized_img = self._image3c.display.scaled(
                        self._move_pos[2], self._move_pos[3],
                        Qt.IgnoreAspectRatio)
                    self.overlabel_display.setPixmap(
                        QPixmap.fromImage(resized_img))
                    self._resizing_image = False

                self.overlabel_display.setGeometry(*self._move_pos)

                if isinstance(self.overlabel_display.croping, tuple):
                    painter = QPainter()
                    painter.begin(self)
                    painter.setRenderHint(QPainter.Antialiasing, True)
                    painter.setRenderHint(QPainter.TextAntialiasing, True)
                    painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

                    painter.setPen(
                        QPen(QColor(*self._args.positive_color),
                             self._args.positive_wid))

                    painter.drawLine(
                        QPoint(
                            self.overlabel_display.croping[0] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), 0),
                        QPoint(
                            self.overlabel_display.croping[0] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), self.height()))
                    painter.drawLine(
                        QPoint(
                            0, self.overlabel_display.croping[1] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()),
                        QPoint(
                            self.width(), self.overlabel_display.croping[1] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()))

                    painter.drawLine(
                        QPoint(
                            self.overlabel_display.croping[2] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), 0),
                        QPoint(
                            self.overlabel_display.croping[2] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), self.height()))
                    painter.drawLine(
                        QPoint(
                            0, self.overlabel_display.croping[3] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()),
                        QPoint(
                            self.width(), self.overlabel_display.croping[3] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()))

                    painter.end()

                    self.ps_status_changed.emit(
                        (self._image3c.rgb_data.shape[1],
                         self._image3c.rgb_data.shape[0], "{:.1f}".format(
                             self.overlabel_display.croping[2] * 100),
                         "{:.1f}".format(self.overlabel_display.croping[3] *
                                         100)))

                elif isinstance(self.overlabel_display.locating, tuple):
                    painter = QPainter()
                    painter.begin(self)
                    painter.setRenderHint(QPainter.Antialiasing, True)
                    painter.setRenderHint(QPainter.TextAntialiasing, True)
                    painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

                    painter.setPen(
                        QPen(QColor(*self._args.positive_color),
                             self._args.positive_wid))

                    painter.drawLine(
                        QPoint(
                            self.overlabel_display.locating[0] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), 0),
                        QPoint(
                            self.overlabel_display.locating[0] *
                            self.overlabel_display.width() +
                            self.overlabel_display.x(), self.height()))
                    painter.drawLine(
                        QPoint(
                            0, self.overlabel_display.locating[1] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()),
                        QPoint(
                            self.width(), self.overlabel_display.locating[1] *
                            self.overlabel_display.height() +
                            self.overlabel_display.y()))

                    painter.end()

                    self.ps_status_changed.emit(
                        (self._image3c.rgb_data.shape[1],
                         self._image3c.rgb_data.shape[0], "{:.1f}".format(
                             self.overlabel_display.locating[0] * 100),
                         "{:.1f}".format(self.overlabel_display.locating[1] *
                                         100)))

                elif self.overlabel_display.locations[
                        self._args.sys_activated_idx]:
                    self.ps_status_changed.emit(
                        (self._image3c.rgb_data.shape[1],
                         self._image3c.rgb_data.shape[0],
                         "{:.1f}".format(self.overlabel_display.locations[
                             self._args.sys_activated_idx][0] * 100),
                         "{:.1f}".format(self.overlabel_display.locations[
                             self._args.sys_activated_idx][1] * 100)))

                else:
                    self.ps_status_changed.emit(
                        (self._image3c.rgb_data.shape[1],
                         self._image3c.rgb_data.shape[0]))
示例#42
0
    def paintEvent(self, event):
        super().paintEvent(event)

        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.TextAntialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

        idx_seq = list(range(5))
        idx_seq = idx_seq[self._args.sys_activated_idx +
                          1:] + idx_seq[:self._args.sys_activated_idx + 1]

        for idx in idx_seq:
            if self.locations[idx]:
                pt_xy = np.array((self.locations[idx][0] * self.width(),
                                  self.locations[idx][1] * self.height()))
                pt_box = get_outer_box(pt_xy, self._args.circle_dist)

                if idx == self._args.sys_activated_idx:
                    painter.setPen(
                        QPen(QColor(*self._args.positive_color),
                             self._args.positive_wid))

                else:
                    painter.setPen(
                        QPen(QColor(*self._args.negative_color),
                             self._args.negative_wid))

                painter.setBrush(QColor(*self._args.sys_color_set[idx].rgb))
                painter.drawEllipse(*pt_box)

        if isinstance(self.croping, tuple):
            painter.setPen(QPen(Qt.NoPen))
            painter.setBrush(QColor(255, 255, 255, 160))

            croping = self.sort_croping()
            croping = (int(self.width() * croping[0]),
                       int(self.height() * croping[1]),
                       int(self.width() * croping[2]),
                       int(self.height() * croping[3]))
            self.draw_rect(painter, 0, 0, croping[0], self.height())
            self.draw_rect(painter, croping[2], 0, self.width(), self.height())
            self.draw_rect(painter, croping[0], 0, croping[2], croping[1])
            self.draw_rect(painter, croping[0], croping[3], croping[2],
                           self.height())

            painter.setPen(
                QPen(QColor(*self._args.positive_color),
                     self._args.positive_wid))
            painter.setBrush(QBrush(Qt.NoBrush))

            if 0 <= self.croping[0] <= self.width():
                painter.drawLine(
                    QPoint(self.croping[0] * self.width(), 0),
                    QPoint(self.croping[0] * self.width(), self.height()))

            if 0 <= self.croping[1] <= self.height():
                painter.drawLine(
                    QPoint(0, self.croping[1] * self.height()),
                    QPoint(self.width(), self.croping[1] * self.height()))

            if 0 <= self.croping[2] <= self.width():
                painter.drawLine(
                    QPoint(self.croping[2] * self.width(), 0),
                    QPoint(self.croping[2] * self.width(), self.height()))

            if 0 <= self.croping[3] <= self.height():
                painter.drawLine(
                    QPoint(0, self.croping[3] * self.height()),
                    QPoint(self.width(), self.croping[3] * self.height()))

        elif isinstance(self.locating, tuple):
            painter.setPen(QPen(Qt.NoPen))
            painter.setBrush(QColor(255, 255, 255, 160))

            painter.drawRect(0, 0, self.width(), self.height())

            painter.setPen(
                QPen(QColor(*self._args.positive_color),
                     self._args.positive_wid))
            painter.setBrush(QBrush(Qt.NoBrush))

            if 0 <= self.locating[0] <= self.width():
                painter.drawLine(
                    QPoint(self.locating[0] * self.width(), 0),
                    QPoint(self.locating[0] * self.width(), self.height()))

            if 0 <= self.locating[1] <= self.height():
                painter.drawLine(
                    QPoint(0, self.locating[1] * self.height()),
                    QPoint(self.width(), self.locating[1] * self.height()))

        elif self.croping or self.locating:
            painter.setPen(QPen(Qt.NoPen))
            painter.setBrush(QColor(255, 255, 255, 160))

            painter.drawRect(0, 0, self.width(), self.height())

        painter.end()
示例#43
0
 def paintEvent(self, event):
     if self.do_paint:
         qp = QPainter()
         qp.begin(self)
         self.draw_flag(qp)
         qp.end()
示例#44
0
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHint(QPainter.Antialiasing)
     self.drawBezierCurve(qp)
     qp.end()
示例#45
0
 def paintEvent(self, event):
     p = QPainter()
     p.begin(self)
     self.drawFunc(event, p)
     p.end()
示例#46
0
class DrawingWidget(QWidget):
    def __init__(self, scale=10, a=1.0, b=1.0, c=0.0, d=1.0):
        super().__init__()

        self.a, self.b, self.c, self.d = a, b, c, d
        self.scale_x, self.scale_y = scale, 0
        self.width, self.height = 0, 0
        self.dx, self.dy = 0, 0
        self.mouse_click_x = -1
        self.mouse_click_y = -1
        self.qp = QPainter()

        self.initUI()

    def initUI(self):
        self.setGeometry(150, 150, 900, 900)
        # self.timer = QBasicTimer()
        # self.timer.start(15, self)
        self.setWindowTitle('Drawing')
        self.show()

    def paintEvent(self, event):
        self.qp.setPen(Qt.black)
        self.qp.begin(self)

        self.draw()
        self.qp.end()

    def resizeEvent(self, event):
        new_width = event.size().width()
        new_height = event.size().height()
        self.width = new_width
        self.height = new_height
        self.scale_y = self.scale_x  # new_width * 6 / new_height

    def draw(self):
        # self.draw_parabola()
        # self.draw_parabola_dists()
        self.draw_parabola_deltas()
        self.draw_axes()

    def draw_axes(self):
        a_, b_, c_, d_ = self.a, self.b, self.c, self.d
        if a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_
            c_ = -c_

        dx = self.get_screen_x(0) - self.get_screen_x(c_)
        dy = self.get_screen_y(d_ - b_) - self.get_screen_y(0)
        self.qp.setPen(Qt.black)
        self.qp.translate(dx, dy)

        self.qp.drawLine(-self.width / 2 - dx, 0, self.width / 2 - dx, 0)
        self.qp.drawLine(0, -self.height / 2 - dy, 0, self.height / 2 - dy)

    def draw_parabola_dists(self):
        self.qp.setPen(Qt.darkBlue)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, c_ = self.a, self.c
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_

        bound = self.width
        f = self.get_screen_x(1 / (4 * a_)) - self.get_screen_x(0)
        x, y = 0, 0
        self.qp.drawPoint(x, y)

        while x <= bound:
            d1 = (f - x)**2 + (-(y + 1))**2 - (-f - x)**2
            min_d = abs(d1)
            n_x, n_y = x, y + 1

            d2 = (f - (x + 1))**2 + (-(y + 1))**2 - (-f - (x + 1))**2
            if abs(d2) < min_d:
                n_x, n_y = x + 1, y + 1
                min_d = abs(d2)

            d3 = (f - (x + 1))**2 + (-y)**2 - (-f - (x + 1))**2
            if abs(d3) < min_d:
                n_x, n_y = x + 1, y

            self.qp.drawPoint(n_x, n_y)
            self.qp.drawPoint(n_x, -n_y)
            x, y = n_x, n_y

    def draw_parabola_deltas(self):
        self.qp.setPen(Qt.red)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, c_ = self.a, self.c
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_

        bound = self.width
        p = self.get_screen_x(1 / (2 * a_)) - self.get_screen_x(0)
        x, y = 0, 0
        self.qp.drawPoint(x, y)

        p2 = 2 * p
        while x <= bound:
            delta = (y + 1) * (y + 1) - p2 * (x + 1)
            if delta < 0:
                other = delta + p2
                if abs(delta) < abs(other):
                    x, y = x + 1, y + 1
                else:
                    x, y = x, y + 1
            else:
                other = delta - 2 * y - 1
                if abs(delta) < abs(other):
                    x, y = x + 1, y + 1
                else:
                    x, y = x + 1, y

            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)

    def draw_parabola(self):
        self.qp.setPen(Qt.black)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, b_, c_, d_ = self.a, self.b, self.c, self.d
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_
            c_ = -c_

        bound = self.width
        p = self.get_screen_x(1 / (2 * a_)) - self.get_screen_x(0)

        p2 = 2 * p
        p4 = 2 * p2
        x, y = 0, 0
        d = 1 - p

        while (y < p) and (x <= bound):
            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)
            if d >= 0:
                x += 1
                d -= p2
            y += 1
            d += (2 * y + 1)

        if d == 1:
            d = 1 - p4
        else:
            d = 1 - p2

        # self.qp.drawLine(x, 0, x, y)
        while x <= bound:
            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)
            if d <= 0:
                y += 1
                d += 4 * y
            x += 1
            d -= p4

    def get_screen_x(self, x):
        return ((self.scale_x / 2 + x) / self.scale_x) * self.width

    def get_screen_y(self, y):
        return ((self.scale_y / 2 + y) / self.scale_y) * self.height

    def timerEvent(self, event):
        self.a += 0.15
        if self.a > 10:
            self.a = -10

        self.repaint()
示例#47
0
 def paintEvent(self, event):
     ap = QPainter()
     ap.begin(self)
     self.drawWidget(ap)
     ap.end()
示例#48
0
 def ppe(self, event):
     qp = QPainter()
     qp.begin(self)
     self.drawFlag(qp)
     qp.end()
示例#49
0
    def paintEvent(self, event):

        qp = QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()
示例#50
0
    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawWidget(qp)
        qp.end()
def parse_terrain_to_image(terrainfile, waterheight=None):
    # In BWii the entry at position 1 is not KNHC, but something else that needs to be skipped
    if terrainfile.entries[1].name != b"KNHC":
        off = 1
    else:
        off = 0

    tiles = terrainfile.entries[1 + off]  # KNHC
    #tiles2 = terrainfile.entries[4+off] # TWCU
    tilemap = terrainfile.entries[3 + off]  # PAMC
    #tilemapdata = bytes(tilemap.data)
    pic = QImage(64 * 4 * 4, 64 * 4 * 4, QImage.Format_ARGB32)
    light_pic = QImage(64 * 4 * 4, 64 * 4 * 4, QImage.Format_ARGB32)

    #colortransition = QImage(os.path.join("lib", "colors_terrainview.png"), "PNG")
    #colors = []

    #for i in range(colortransition.width()):
    #    colors.append(colortransition.pixel(i, 0))
    """new = QImage(len(colors), 200, QImage.Format_ARGB32)
    trans_painter = QPainter()
    trans_painter.begin(new)
    for i in range(len(colors)):
        r, g, b = colors[i]
        pen = trans_painter.pen()
        pen.setColor(QColor(r, g, b))
        trans_painter.setPen(pen)
        for y in range(200):
            trans_painter.drawPoint(i, y)

    trans_painter.end()
    result = new.save("transition.png", "PNG")
    print("saved", result)"""
    #pic = QPixmap(64*4*4, 64*4*4)
    p = QPainter()
    p.begin(pic)
    light_p = QPainter()
    light_p.begin(light_pic)
    biggestheight = 0
    lowest = 0xFFFF
    print(len(tiles.data) / (180 * 16))
    heights = []
    watercolor = (106, 152, 242)

    lowest_values = {}
    total_lowest_color = None
    outofbounds_count = 0

    for x in range(64):
        for y in range(64):
            a, b, offset = struct.unpack(
                ">BBH", tilemap.data[(y * 64 + x) * 4:(y * 64 + x + 1) * 4])
            #print(a,b,offset)
            if b == 1:
                tiles_data = tiles.data[180 * 16 * offset:180 * 16 *
                                        (offset + 1)]
                lowest = 0xFFFF
                lowest_color = None
                for ix in range(4):
                    for iy in range(4):
                        coord_offset = iy * 4 + ix
                        single_tile = tiles_data[180 * (coord_offset):180 *
                                                 (coord_offset + 1)]
                        if len(single_tile) == 0:
                            print("Ooops:", offset)
                        for iix in range(4):
                            for iiy in range(4):
                                point_offset = iiy * 4 + iix
                                #print("do stuff", (y*64+x)*4)
                                height = struct.unpack(
                                    ">H",
                                    single_tile[point_offset *
                                                2:(point_offset + 1) * 2])[0]

                                light_r, light_g, light_b, unused = struct.unpack(
                                    "BBBB",
                                    single_tile[32 + point_offset * 4:32 +
                                                (point_offset + 1) * 4])
                                #blend_r, blend_g, blend_b, wat = struct.unpack("BBBB",
                                #                                                     single_tile[4+32+64+point_offset*4:4+32+64+(point_offset+1)*4])
                                pen = p.pen()
                                """if height > biggestheight:
                                    biggestheight = height
                                if height < lowest:
                                    lowest = height
                                if height not in heights:
                                    heights.append(height)
                                if height >= 0x4FF:
                                    height -= 0x4FF
                                    pen.setColor(QColor(((height>>2)+50)&0xFF, ((height>>2)+50)&0xFF, ((height>>2)+50)&0xFF))
                                elif height >= 0x3F0:
                                    height -= 0x3F0
                                    pen.setColor(QColor(((height>>2)+90)&0xFF, ((height>>2)+30)&0xFF, ((height>>2)+30)&0xFF))
                                elif height >= 0x1FF:
                                    height -= 0x1FF
                                    pen.setColor(QColor(0, ((height>>2)+30)&0xFF, 0))
                                else:
                                    pen.setColor(QColor(0, 0, ((height>>2)+30)&0xFF))"""

                                if height >= len(COLORS):

                                    #print("oops, color out of bounds:", height, len(COLORS))
                                    outofbounds_count += 1
                                    height = len(COLORS) - 1

                                r, g, b = COLORS[height]
                                if waterheight is not None and height <= waterheight * 16:
                                    r = (r + watercolor[0]) // 2
                                    g = (r + watercolor[1]) // 2
                                    b = (b + watercolor[2]) // 2
                                    #r, g, b = watercolor
                                if height < lowest:  #and height > 0:
                                    lowest = height
                                    lowest_color = (r, g, b)
                                    total_lowest_color = (r, g, b)
                                pen.setColor(QColor(r, g, b))
                                #pen.setColor(QColor(light_r, light_g, light_b))

                                #pen.setColor(QColor(blend_r, blend_g, blend_b))
                                #pen.setColor(QColor(blend_r, blend_g, blend_b))

                                #pen.setColor(QColor(height>>8, height&0xFF, height&0xFF))
                                p.setPen(pen)
                                p.drawPoint(x * 16 + ix * 4 + iix,
                                            y * 16 + iy * 4 + iiy)
                                pen.setColor(QColor(light_r, light_g, light_b))
                                light_p.setPen(pen)
                                light_p.drawPoint(x * 16 + ix * 4 + iix,
                                                  y * 16 + iy * 4 + iiy)

                lowest_values[(x, y)] = lowest_color
    p.end()
    light_p.end()

    print(pic.size().height(), pic.size().width())
    print(biggestheight, hex(biggestheight))
    print(lowest, hex(lowest))
    heights.sort()
    print(heights)
    if outofbounds_count > 0:
        print("{0} points out of bounds".format(outofbounds_count))

    finalimage = QImage(pic.width(), pic.height(), QImage.Format_ARGB32)
    p.begin(finalimage)

    #common_lowest_values =
    if waterheight is not None:
        """neighbours = {}
        for x in range(64):
            for y in range(64):

                if (x,y) in lowest_values:

                    for i in range(-1, 1+1):
                        for j in range(-1, 1+1):

                            if (x+i, y+j) not in lowest_values:
                                if (x+i, y+j) not in neighbours:
                                    neighbours[(x+i, y+j)] = [lowest_values[(x,y)]]
                                else:
                                    neighbours[((x+i, y+j))].append(lowest_values[(x,y)])

        all_lowest_values = []
        for pos, values in neighbours.items():
            all_lowest_values.extend(values)
            r, g, b = values[0]
            if len(values) > 1:
                for r2, g2, b2 in values[1:]:
                    r = (r+r2)//2
                    g = (g+g2)//2
                    b = (b+b2)//2
            current = 0#sum(values) // len(values)
            x,y = pos
            #r, g, b = colors[current]


        #all_lowest = sum(all_lowest_values) // len(all_lowest_values)

        #watercolor = (106, 152, 242) #colors[0x4F]
        color = colors[lowest]
        print("LOWEST IS", lowest)
        print(neighbours)
        r = (color[0]+watercolor[0]) // 2
        g = (color[1]+watercolor[1]) // 2
        b = (color[2]+watercolor[2]) // 2"""
        p.fillRect(
            0, 0, 64 * 64 * 4, 64 * 64 * 4,
            QColor(total_lowest_color[0], total_lowest_color[1],
                   total_lowest_color[2]))
    p.drawImage(0, 0, pic)
    p.end()
    """p.begin(self.terrainview)
    p.drawImage(0, 0, pic)
    p.end()"""

    return finalimage.mirrored(False, True), light_pic.mirrored(
        False, True)  #pic.mirrored(False, True)
示例#52
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     self.circle(painter)
     painter.end()
示例#53
0
	def paintEvent(self, e):
		qp = QPainter()
		qp.begin(self)
		self.PaintDashLine(qp)
		qp.end()
示例#54
0
    def renderContact(self, generator):
        """Render the contact with the defined colors."""
        # startx = 90
        # orig_startx = startx
        start_text = 10
        rowheight = 22
        textoffset = 12
        blackColor = QColor(0, 0, 0)
        whiteColor = QColor(255, 255, 255)

        merge = self.merge
        offset = 10

        self.labelView.clean()
        self.labelView = LabelView(self.contacts)
        self.labelView.setParent(self)
        self.labelView.nsPerFrame = self.nsPerFrame
        self.labelView.threshold = self.threshold
        self.labelView.show()
        # startx has to be set according to maximum button length in labelview
        startx = np.max(self.labelView.buttonWidths) + 15
        orig_startx = startx

        # probably included in next version...
        # if self.vismode:
        #     textoffset += 15
        #     start_text += 15
        #     startx += 15
        #     orig_startx += 15

        # print(orig_startx)
        self.timeLineXOrigin = orig_startx
        self.rowh = rowheight

        # self.sizeX = (len(self.contacts[0].scoreArray) + startx) * offset
        # self.sizeY = len(self.contacts) * rowheight
        if self.rangeFilterActive:
            self.sizeX = startx + (len(self.contacts[0].scoreArray) +
                                   merge * 2) * offset / merge
        else:
            self.sizeX = startx + (len(self.contacts[0].scoreArray[self.range[0]:self.range[1]]) + merge * 2) \
                                  * offset / merge

        # add one row for frame numbers
        self.sizeY = (len(self.contacts) + 1) * rowheight

        self.pixmap = QPixmap(QSize(self.sizeX, self.sizeY))
        p = QPainter()

        if generator:
            p.begin(generator)
        else:
            p.begin(self.pixmap)

        p.fillRect(0, 0, self.sizeX, self.sizeY, whiteColor)

        row = 0
        rownumber = 0
        # print("merge value", merge)
        for c in self.contacts:
            self.alphaFactor = 50
            bbScColor = BackboneSidechainContactType.colors[
                c.determineBackboneSidechainType()]
            i = 0
            if not self.showHbondScores:
                if self.rangeFilterActive:
                    rangedScores = c.scoreArray
                else:
                    rangedScores = c.scoreArray[self.range[0]:self.range[1]]
            else:
                hbarray = c.hbondFramesScan()
                self.alphaFactor = 100
                if self.rangeFilterActive:
                    rangedScores = hbarray
                else:
                    rangedScores = hbarray[self.range[0]:self.range[1]]
            if rownumber == 0:
                # show the frame numbers on top
                p.setFont(QFont('Arial', 8))
                p.drawText(start_text, row + textoffset + 2.0, "Frame:")

                off = 0
                if self.range[0] != 0:
                    off = 1
                for l in range(self.range[0] + off, self.range[1] + 1,
                               10)[off:]:
                    if l == 0:
                        continue
                    # print(l)
                    # TODO: sometimes errors occur!
                    p.drawText(startx + (l - 1 - self.range[0]) * offset,
                               row + textoffset + 2.0, str(l * merge))
                self.labelView.move(0, rowheight)
                row += rowheight
            while i < len(rangedScores):
                p.setPen(blackColor)
                merged_score = 0
                for j in range(merge):
                    if (i + j) >= len(rangedScores):
                        break
                    x = rangedScores[i + j]
                    merged_score += x
                merged_score /= merge
                alpha = merged_score * self.alphaFactor
                if alpha > 255:
                    alpha = 255
                if self.colorScheme == ColorScheme.bbsc:
                    # pass
                    p.setBrush(
                        QColor(bbScColor[0], bbScColor[1], bbScColor[2],
                               alpha))
                elif self.colorScheme == ColorScheme.custom:
                    color = QColor(self.customColor)
                    color.setAlpha(alpha)
                    p.setBrush(color)

                if rownumber == self.clickedRow:
                    p.setPen(QColor(250, 50, 50))
                else:
                    p.setPen(QColor(0, 0, 0))
                p.drawRect(startx, row, offset, 20)
                startx += offset
                i += merge
            self.offset = offset
            self.endOfTimeLine = startx
            startx = orig_startx
            row += rowheight
            rownumber += 1

        if generator:
            row = rowheight
            for c in self.contacts:
                p.setPen(0)
                # print(ContactType.colors[c.contactType])
                p.setFont(QFont('Arial', 9))
                # string = c.resA + c.residA + "-" + c.resB + c.residB
                string = c.title
                p.setBrush(ContactType.qcolors[c.determine_ctype()])
                p.drawRect(0, row + 3, orig_startx, rowheight - 10)
                p.setPen(1)
                p.drawText(start_text, row + textoffset, string)
                row += rowheight

        p.end()
        self.globalClickedRow = self.clickedRow
        self.clickedRow = -1
示例#55
0
    def overlay_marks(self, img, is_cseed=False, calibration_sheet=False):
        border_color = Qt.white
        base_img = QImage(self.f_size.width(), self.f_size.height(),
                          QImage.Format_ARGB32)
        base_img.fill(border_color)
        img = QImage(img)

        painter = QPainter()
        painter.begin(base_img)

        total_distance_h = round(base_img.width() / self.abstand_v)
        dist_v = round(total_distance_h) / 2
        dist_h = round(total_distance_h) / 2

        img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h)))
        painter.drawImage(total_distance_h, total_distance_h, img)

        #frame around image
        pen = QPen(Qt.black, 2)
        painter.setPen(pen)

        #horz
        painter.drawLine(0, total_distance_h, base_img.width(),
                         total_distance_h)
        painter.drawLine(0,
                         base_img.height() - (total_distance_h),
                         base_img.width(),
                         base_img.height() - (total_distance_h))
        #vert
        painter.drawLine(total_distance_h, 0, total_distance_h,
                         base_img.height())
        painter.drawLine(base_img.width() - (total_distance_h), 0,
                         base_img.width() - (total_distance_h),
                         base_img.height())

        #border around img
        border_thick = 6
        Rpath = QPainterPath()
        Rpath.addRect(
            QRectF((total_distance_h) + (border_thick / 2),
                   (total_distance_h) + (border_thick / 2),
                   base_img.width() - ((total_distance_h) * 2) -
                   ((border_thick) - 1),
                   (base_img.height() -
                    ((total_distance_h)) * 2) - ((border_thick) - 1)))
        pen = QPen(Qt.black, border_thick)
        pen.setJoinStyle(Qt.MiterJoin)

        painter.setPen(pen)
        painter.drawPath(Rpath)

        Bpath = QPainterPath()
        Bpath.addRect(
            QRectF((total_distance_h), (total_distance_h),
                   base_img.width() - ((total_distance_h) * 2),
                   (base_img.height() - ((total_distance_h)) * 2)))
        pen = QPen(Qt.black, 1)
        painter.setPen(pen)
        painter.drawPath(Bpath)

        pen = QPen(Qt.black, 1)
        painter.setPen(pen)
        painter.drawLine(0,
                         base_img.height() / 2, total_distance_h,
                         base_img.height() / 2)
        painter.drawLine(base_img.width() / 2, 0,
                         base_img.width() / 2, total_distance_h)

        painter.drawLine(base_img.width() - total_distance_h,
                         base_img.height() / 2, base_img.width(),
                         base_img.height() / 2)
        painter.drawLine(base_img.width() / 2, base_img.height(),
                         base_img.width() / 2,
                         base_img.height() - total_distance_h)

        #print code
        f_size = 37
        QFontDatabase.addApplicationFont(
            os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf'))
        font = QFont("DejaVu Sans Mono", f_size - 11, QFont.Bold)
        font.setPixelSize(35)
        painter.setFont(font)

        if not calibration_sheet:
            if is_cseed:  #its a secret
                painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
                painter.drawLine(0, dist_v, base_img.width(), dist_v)
                painter.drawLine(dist_h, 0, dist_h, base_img.height())
                painter.drawLine(0,
                                 base_img.height() - dist_v, base_img.width(),
                                 base_img.height() - (dist_v))
                painter.drawLine(base_img.width() - (dist_h), 0,
                                 base_img.width() - (dist_h),
                                 base_img.height())

                painter.drawImage(
                    ((total_distance_h)) + 11, ((total_distance_h)) + 11,
                    QImage(icon_path('electrumb.png')).scaledToWidth(
                        2.1 * (total_distance_h), Qt.SmoothTransformation))

                painter.setPen(QPen(Qt.white, border_thick * 8))
                painter.drawLine(
                    base_img.width() - ((total_distance_h)) -
                    (border_thick * 8) / 2 - (border_thick / 2) - 2,
                    (base_img.height() - ((total_distance_h))) -
                    ((border_thick * 8) / 2) - (border_thick / 2) - 2,
                    base_img.width() - ((total_distance_h)) -
                    (border_thick * 8) / 2 - (border_thick / 2) - 2 - 77,
                    (base_img.height() - ((total_distance_h))) -
                    ((border_thick * 8) / 2) - (border_thick / 2) - 2)
                painter.setPen(QColor(0, 0, 0, 255))
                painter.drawText(
                    QRect(
                        0,
                        base_img.height() - 107,
                        base_img.width() - total_distance_h - border_thick -
                        11,
                        base_img.height() - total_distance_h - border_thick),
                    Qt.AlignRight, self.versioned_seed.version + '_' +
                    self.versioned_seed.checksum)
                painter.end()

            else:  # revealer

                painter.setPen(QPen(border_color, 17))
                painter.drawLine(0, dist_v, base_img.width(), dist_v)
                painter.drawLine(dist_h, 0, dist_h, base_img.height())
                painter.drawLine(0,
                                 base_img.height() - dist_v, base_img.width(),
                                 base_img.height() - (dist_v))
                painter.drawLine(base_img.width() - (dist_h), 0,
                                 base_img.width() - (dist_h),
                                 base_img.height())

                painter.setPen(QPen(Qt.black, 2))
                painter.drawLine(0, dist_v, base_img.width(), dist_v)
                painter.drawLine(dist_h, 0, dist_h, base_img.height())
                painter.drawLine(0,
                                 base_img.height() - dist_v, base_img.width(),
                                 base_img.height() - (dist_v))
                painter.drawLine(base_img.width() - (dist_h), 0,
                                 base_img.width() - (dist_h),
                                 base_img.height())
                logo = QImage(icon_path('revealer_c.png')).scaledToWidth(
                    1.3 * (total_distance_h))
                painter.drawImage((total_distance_h) + (border_thick),
                                  ((total_distance_h)) + (border_thick), logo,
                                  Qt.SmoothTransformation)

                #frame around logo
                painter.setPen(QPen(Qt.black, border_thick))
                painter.drawLine(
                    total_distance_h + border_thick,
                    total_distance_h + logo.height() + 3 * (border_thick / 2),
                    total_distance_h + logo.width() + border_thick,
                    total_distance_h + logo.height() + 3 * (border_thick / 2))
                painter.drawLine(
                    logo.width() + total_distance_h + 3 * (border_thick / 2),
                    total_distance_h + (border_thick),
                    total_distance_h + logo.width() + 3 * (border_thick / 2),
                    total_distance_h + logo.height() + (border_thick))

                #frame around code/qr
                qr_size = 179

                painter.drawLine((base_img.width() - ((total_distance_h)) -
                                  (border_thick / 2) - 2) - qr_size,
                                 (base_img.height() - ((total_distance_h))) -
                                 ((border_thick * 8)) - (border_thick / 2) - 2,
                                 (base_img.width() / 2 +
                                  (total_distance_h / 2) - border_thick -
                                  (border_thick * 8) / 2) - qr_size,
                                 (base_img.height() - ((total_distance_h))) -
                                 ((border_thick * 8)) - (border_thick / 2) - 2)

                painter.drawLine(
                    (base_img.width() / 2 +
                     (total_distance_h / 2) - border_thick -
                     (border_thick * 8) / 2) - qr_size,
                    (base_img.height() - ((total_distance_h))) -
                    ((border_thick * 8)) - (border_thick / 2) - 2,
                    base_img.width() / 2 + (total_distance_h / 2) -
                    border_thick - (border_thick * 8) / 2 - qr_size,
                    ((base_img.height() - ((total_distance_h))) -
                     (border_thick / 2) - 2))

                painter.setPen(QPen(Qt.white, border_thick * 8))
                painter.drawLine(
                    base_img.width() - ((total_distance_h)) -
                    (border_thick * 8) / 2 - (border_thick / 2) - 2,
                    (base_img.height() - ((total_distance_h))) -
                    ((border_thick * 8) / 2) - (border_thick / 2) - 2,
                    base_img.width() / 2 + (total_distance_h / 2) -
                    border_thick - qr_size,
                    (base_img.height() - ((total_distance_h))) -
                    ((border_thick * 8) / 2) - (border_thick / 2) - 2)

                painter.setPen(QColor(0, 0, 0, 255))
                painter.drawText(
                    QRect(((base_img.width() / 2) + 21) - qr_size,
                          base_img.height() - 107,
                          base_img.width() - total_distance_h - border_thick -
                          93,
                          base_img.height() - total_distance_h - border_thick),
                    Qt.AlignLeft,
                    self.versioned_seed.get_ui_string_version_plus_seed())
                painter.drawText(
                    QRect(
                        0,
                        base_img.height() - 107,
                        base_img.width() - total_distance_h - border_thick -
                        3 - qr_size,
                        base_img.height() - total_distance_h - border_thick),
                    Qt.AlignRight, self.versioned_seed.checksum)

                # draw qr code
                qr_qt = self.paintQR(
                    self.versioned_seed.get_ui_string_version_plus_seed() +
                    self.versioned_seed.checksum)
                target = QRectF(base_img.width() - 65 - qr_size,
                                base_img.height() - 65 - qr_size, qr_size,
                                qr_size)
                painter.drawImage(target, qr_qt)
                painter.setPen(QPen(Qt.black, 4))
                painter.drawLine(base_img.width() - 65 - qr_size,
                                 base_img.height() - 65 - qr_size,
                                 base_img.width() - 65 - qr_size,
                                 (base_img.height() - ((total_distance_h))) -
                                 ((border_thick * 8)) - (border_thick / 2) - 4)
                painter.drawLine(base_img.width() - 65 - qr_size,
                                 base_img.height() - 65 - qr_size,
                                 base_img.width() - 65,
                                 base_img.height() - 65 - qr_size)
                painter.end()

        else:  # calibration only
            painter.end()
            cal_img = QImage(self.f_size.width() + 100,
                             self.f_size.height() + 100, QImage.Format_ARGB32)
            cal_img.fill(Qt.white)

            cal_painter = QPainter()
            cal_painter.begin(cal_img)
            cal_painter.drawImage(0, 0, base_img)

            #black lines in the middle of border top left only
            cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
            cal_painter.drawLine(0, dist_v, base_img.width(), dist_v)
            cal_painter.drawLine(dist_h, 0, dist_h, base_img.height())

            pen = QPen(Qt.black, 2, Qt.DashDotDotLine)
            cal_painter.setPen(pen)
            n = 15

            cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold))
            for x in range(-n, n):
                #lines on bottom (vertical calibration)
                cal_painter.drawLine((((base_img.width()) / (n * 2)) *
                                      (x)) + (base_img.width() / 2) - 13,
                                     x + 2 + base_img.height() - (dist_v),
                                     (((base_img.width()) / (n * 2)) *
                                      (x)) + (base_img.width() / 2) + 13,
                                     x + 2 + base_img.height() - (dist_v))

                num_pos = 9
                if x > 9: num_pos = 17
                if x < 0: num_pos = 20
                if x < -9: num_pos = 27

                cal_painter.drawText((((base_img.width()) / (n * 2)) *
                                      (x)) + (base_img.width() / 2) - num_pos,
                                     50 + base_img.height() - (dist_v), str(x))

                #lines on the right (horizontal calibrations)

                cal_painter.drawLine(
                    x + 2 + (base_img.width() - (dist_h)),
                    ((base_img.height() / (2 * n)) * (x)) +
                    (base_img.height() / n) + (base_img.height() / 2) - 13,
                    x + 2 + (base_img.width() - (dist_h)),
                    ((base_img.height() / (2 * n)) * (x)) +
                    (base_img.height() / n) + (base_img.height() / 2) + 13)

                cal_painter.drawText(30 + (base_img.width() - (dist_h)),
                                     ((base_img.height() / (2 * n)) *
                                      (x)) + (base_img.height() / 2) + 13,
                                     str(x))

            cal_painter.end()
            base_img = cal_img

        return base_img
示例#56
0
文件: ui.py 项目: dturecek/dicewars
class MainWindow(QWidget):
    """Main window of the GUI containing the game board
    """
    def __init__(self, game):
        """
        Parameters
        ----------
        game : Game
        """
        self.logger = logging.getLogger('GUI')
        super(MainWindow, self).__init__()
        self.qp = QPainter()

        self.game = game
        self.board = game.board
        self.areas_mapping = {}
        for i, area in self.board.areas.items():
            for h in area.get_hexes():
                self.areas_mapping[h] = i

        self.font = QFont('Helvetica', 16)
        self.pen = QPen()
        self.pen.setWidth(2)

        self.activated_area_name = None

    def paintEvent(self, event):
        self.qp.begin(self)
        self.draw_areas()
        self.qp.end()

    def draw_areas(self):
        """Draw areas in the game board
        """
        if self.game.draw_battle:
            self.activated_area_name = None
            self.game.draw_battle = False
        size = self.size()
        x = size.width()
        y = size.height()

        bbox = hexutil.Rectangle(-x // 2, -y // 2, x, y)
        hexgrid = hexutil.HexGrid(10)

        self.qp.setPen(Qt.NoPen)
        self.qp.translate(x // 2, y // 2)

        for k, area in self.board.areas.items():
            lines = []
            first_hex = True

            color = player_color(area.get_owner_name())
            if self.activated_area_name == int(k):
                color = (170 + color[0] // 3, 170 + color[1] // 3,
                         170 + color[2] // 3)
            self.qp.setBrush(QColor(*color))
            self.qp.setPen(Qt.NoPen)
            for h in area.get_hexes():
                polygon = QPolygon(
                    [QPoint(*corner) for corner in hexgrid.corners(h)])
                self.qp.drawPolygon(polygon)

                if first_hex:
                    self.qp.save()
                    rect = QRectF(*hexgrid.bounding_box(h))
                    self.qp.setBrush(QColor(0, 0, 0))
                    self.qp.setPen(self.pen)
                    self.qp.setFont(self.font)
                    self.qp.setRenderHint(QPainter.TextAntialiasing)

                    self.qp.drawText(rect, Qt.AlignCenter,
                                     str(area.get_dice()))
                    first_hex = False
                    self.qp.restore()

                for n in h.neighbours():
                    if n not in area.get_hexes():
                        line = []
                        for corner in hexgrid.corners(h):
                            if corner in hexgrid.corners(n):
                                line.append(corner)
                        lines.append(line)

            self.qp.save()
            pen = QPen()
            pen.setWidth(3)
            self.qp.setPen(pen)
            self.qp.setBrush(QColor())
            self.qp.setRenderHint(QPainter.Antialiasing)
            for line in lines:
                self.qp.drawLine(line[0][0], line[0][1], line[1][0],
                                 line[1][1])
            self.qp.restore()

    def mousePressEvent(self, event):
        hexagon = self.get_hex(event.pos())
        try:
            area = self.board.get_area(self.areas_mapping[hexagon])

            if self.activated_area_name:
                if area.get_name() == self.activated_area_name:
                    self.activated_area_name = None
                    self.update()
                elif (area.get_name()
                      in self.activated_area.get_adjacent_areas()
                      and area.get_owner_name() !=
                      self.game.current_player.get_name()):
                    # attack
                    self.game.send_message('battle', self.activated_area_name,
                                           area.get_name())
            elif (area.get_owner_name() == self.game.player_name and
                  self.game.player_name == self.game.current_player.get_name()
                  and area.has_dice()):
                # area activation
                self.activated_area_name = area.get_name()
                self.activated_area = area
                self.update()
        except KeyError:
            pass

    def get_hex(self, position):
        """Return coordinates of a Hex from the given pixel position
        """
        size = self.size()
        x = size.width() // 2
        y = size.height() // 2
        hexgrid = hexutil.HexGrid(10)
        return hexgrid.hex_at_coordinate(position.x() - x, position.y() - y)
    def generate_image(self):
        """Generate image."""
        l_top = self.dockwidget.map_layer_combobox_1.currentLayer()
        l_bottom = self.dockwidget.map_layer_combobox_2.currentLayer()

        # TODO: QgsRuleBasedRenderer to manage later
        # TODO: Filter based on renderer type
        if (l_top.id() != l_bottom.id()):

            colors_layer_top = self.get_colors_from_layer(
                l_top, self.reverse_layer_top_colors)
            colors_layer_bottom = self.get_colors_from_layer(
                l_bottom, self.reverse_layer_bottom_colors)

            # Set default values
            len_color_layer_top = len(colors_layer_top)
            len_color_layer_bottom = len(colors_layer_bottom)

            # Draw image on top
            img_top = self.generate_image_for_colors(colors_layer_top,
                                                     len_color_layer_bottom,
                                                     len_color_layer_top,
                                                     self.square_width_cell,
                                                     reverse=False)
            img_bottom = self.generate_image_for_colors(colors_layer_bottom,
                                                        len_color_layer_bottom,
                                                        len_color_layer_top,
                                                        self.square_width_cell,
                                                        reverse=True)

            # Create a new painter to merge images
            painter = QPainter()
            # Declare transform function to rotate axis to switch x and y
            trans = QTransform()

            # Start from first image
            painter.begin(img_top)
            # Apply blending/composition
            painter.setCompositionMode(self.blend_mode)
            # TODO: Manage border when pen color
            painter.drawImage(0, 0, img_bottom)
            painter.end()

            # Rotate if necessary
            if self.invert_axis:
                trans = QTransform()
                trans.rotate(90)
                img_top = img_top.transformed(trans)

            # Reuse end image and display it in an UI overview
            item = QPixmap.fromImage(img_top)
            scene = QGraphicsScene()
            scene.addPixmap(item)
            self.dockwidget.graphic_preview.setScene(scene)
            # Keep reference to image to ease image export
            self.image_output = img_top
        else:
            self.iface.messageBar().pushMessage("Information",
                                                """Choose two different layers.
                Otherwise, no image overview will be generated.
                """,
                                                level=Qgis.Info)
示例#58
0
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     self.drawRectangles(qp)
     qp.end()
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     self.drawMandelbrot(qp)
     qp.end()
    def paintEvent(self, event):
        self.setWindowTitle('QBrush Function Test')
        self.move(0, 0)
        self.setFixedSize(860, 480)
        paint = QPainter()
        paint.begin(self)
        brush = QBrush(Qt.SolidPattern)
        paint.setBrush(brush)
        paint.drawRect(10, 15, 90, 60)

        brush = QBrush(Qt.Dense1Pattern)
        paint.setBrush(brush)
        paint.drawRect(135, 15, 90, 60)

        brush = QBrush(Qt.Dense2Pattern)
        paint.setBrush(brush)
        paint.drawRect(250, 15, 90, 60)

        brush = QBrush(Qt.Dense3Pattern)
        paint.setBrush(brush)
        paint.drawRect(375, 15, 90, 60)

        brush = QBrush(Qt.Dense4Pattern)
        paint.setBrush(brush)
        paint.drawRect(500, 15, 90, 60)

        brush = QBrush(Qt.Dense5Pattern)
        paint.setBrush(brush)
        paint.drawRect(625, 15, 90, 60)

        brush = QBrush(Qt.Dense6Pattern)
        paint.setBrush(brush)
        paint.drawRect(10, 115, 90, 60)

        brush = QBrush(Qt.Dense7Pattern)
        paint.setBrush(brush)
        paint.drawRect(135, 115, 90, 60)

        brush = QBrush(Qt.BDiagPattern)
        paint.setBrush(brush)
        paint.drawRect(250, 115, 90, 60)

        brush = QBrush(Qt.CrossPattern)
        paint.setBrush(brush)
        paint.drawRect(375, 115, 90, 60)

        brush = QBrush(Qt.DiagCrossPattern)
        paint.setBrush(brush)
        paint.drawRect(500, 115, 90, 60)

        brush = QBrush(Qt.ConicalGradientPattern)
        paint.setBrush(brush)
        paint.drawRect(625, 115, 90, 60)

        brush = QBrush(Qt.FDiagPattern)
        paint.setBrush(brush)
        paint.drawRect(10, 205, 90, 60)

        brush = QBrush(Qt.HorPattern)
        paint.setBrush(brush)
        paint.drawRect(135, 205, 90, 60)

        brush = QBrush(Qt.LinearGradientPattern)
        paint.setBrush(brush)
        paint.drawRect(250, 205, 90, 60)

        brush = QBrush(Qt.RadialGradientPattern)
        paint.setBrush(brush)
        paint.drawRect(375, 205, 90, 60)

        brush = QBrush(Qt.TexturePattern)
        paint.setBrush(brush)
        paint.drawRect(500, 205, 90, 60)

        brush = QBrush(Qt.VerPattern)
        paint.setBrush(brush)
        paint.drawRect(625, 205, 90, 60)

        paint.end()