示例#1
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()
示例#2
0
def pixmap(name, size, mode, state):
    """Returns a (possibly cached) pixmap of the name and size with the default text color.
    
    The state argument is ignored for now.
    
    """
    if mode == QIcon.Selected:
        color = QApplication.palette().highlightedText().color()
    else:
        color = QApplication.palette().text().color()
    key = (name, size.width(), size.height(), color.rgb(), mode)
    try:
        return _pixmaps[key]
    except KeyError:
        i = QImage(size, QImage.Format_ARGB32_Premultiplied)
        i.fill(0)
        painter = QPainter(i)
        # render SVG symbol
        QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter)
        # recolor to text color
        painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        painter.fillRect(i.rect(), color)
        painter.end()
        # let style alter the drawing based on mode, and create QPixmap
        pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption())
        _pixmaps[key] = pixmap
        return pixmap
示例#3
0
    def setupScene(self):
        self.m_scene.setSceneRect(-300, -200, 600, 460)

        linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100))
        linearGrad.setColorAt(0, Qt.darkGreen)#QColor(255, 255, 255))
        linearGrad.setColorAt(1, Qt.green)#QQColor(192, 192, 255))
        self.setBackgroundBrush(linearGrad)

        radialGrad = QRadialGradient(30, 30, 30)
        radialGrad.setColorAt(0, Qt.yellow)
        radialGrad.setColorAt(0.2, Qt.yellow)
        radialGrad.setColorAt(1, Qt.transparent)

        pixmap = QPixmap(60, 60)
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.setBrush(radialGrad)
        painter.drawEllipse(0, 0, 60, 60)
        painter.end()

        self.m_lightSource = self.m_scene.addPixmap(pixmap)
        self.m_lightSource.setZValue(2)

        self.proto = ProtoObj(0, 0, 50, 50, self)
        self.proto.initObj()

        #self.m_items.append(self.proto.getObj()[0])
        self.m_scene.addItem(self.proto.getObj()[0])
示例#4
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)
示例#5
0
 def _render_qwebpage_full(self, web_rect, render_rect, canvas_size):
     """Render web page in one step."""
     if self._qpainter_needs_tiling(render_rect, canvas_size):
         # If this condition is true, this function may get stuck.
         raise ValueError("Rendering region is too large to be drawn"
                          " in one step, use tile-by-tile renderer instead")
     canvas = QImage(canvas_size, self.qt_image_format)
     if self.is_jpeg():
         # White background for JPEG images, same as we have in all browsers.
         canvas.fill(Qt.white)
     else:
         # Preserve old behaviour for PNG format.
         canvas.fill(0)
     painter = QPainter(canvas)
     try:
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setRenderHint(QPainter.TextAntialiasing, True)
         painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
         painter.setWindow(web_rect)
         painter.setViewport(render_rect)
         painter.setClipRect(web_rect)
         self.web_page.mainFrame().render(painter)
     finally:
         painter.end()
     return WrappedQImage(canvas)
示例#6
0
    def draw_indicator(indicator: int):
        pixmap = QPixmap(24, 24)

        painter = QPainter(pixmap)
        w, h = pixmap.width(), pixmap.height()

        painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255))))

        pen = QPen(QColor("white"))
        pen.setWidth(2)
        painter.setPen(pen)

        font = util.get_monospace_font()
        font.setBold(True)
        font.setPixelSize(16)
        painter.setFont(font)

        f = QFontMetrics(painter.font())
        indicator_str = str(indicator) if indicator < 10 else "+"

        fw = f.width(indicator_str)
        fh = f.height()
        painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str)

        painter.end()
        return QIcon(pixmap)
 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)
	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()
示例#9
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()
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 paintEvent(self, e):
        print("Paint event")

        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()
示例#12
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()
示例#13
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)
示例#14
0
class RoundedPushButton1(QPushButton):
    def __init__(self,parent, default_wide, default_high,text=''):
        QPushButton.__init__(self, parent)
        #self.resize(100,80)
        self.default_high=default_high
        self.default_wide=default_wide
        self.xrd=self.default_wide/10
        #self.yrd=self.default_high/10
        self.yrd=self.xrd
        #self.resize(self.default_wide,self.default_high)

        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(0)
        self.brush=QBrush(Qt.SolidPattern)

        self.textlabel=textQLabel(self,text)

    def paintEvent(self,event):
        #brush.setStyle(Qt.Dense1Pattern)
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)
        
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawRoundedRect(QRect(0,0,self.default_wide,self.default_high), self.xrd, self.yrd)
        #self.painter.drawPixmap(self.imgx, self.imgy, self.piximg)
        self.painter.end()
示例#15
0
class ModCrossButton(QPushButton):
    def __init__(self,parent,path=None):
        QPushButton.__init__(self,parent)

        self.parent=parent


        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)


    def paintEvent(self,event):
        self.wide=self.width()
        self.high=self.height()
        self.xdis=self.wide/7
        self.ydis=self.xdis

        self.path=QPainterPath()
        self.path.setFillRule(Qt.OddEvenFill)

        self.path.moveTo(self.wide/2, self.high/2-self.xdis)
        self.path.arcTo(0,0, self.wide, self.high,0,360)
        #self.path.closeSubpath()

        self.path.moveTo(self.wide/2-self.xdis/2, self.ydis)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high/2-self.xdis/2)
        self.path.lineTo(self.ydis, self.high/2-self.xdis/2)
        self.path.lineTo(self.ydis, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high-self.ydis)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high-self.ydis)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide-self.ydis, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide-self.ydis, self.high/2-self.xdis/2)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high/2-self.xdis/2)
        self.path.lineTo(self.wide/2+self.xdis/2, self.ydis)
        self.path.closeSubpath()

        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)

        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawPath(self.path)
        self.painter.end()

    #def mousePressEvent(self,ev):
    #    self.parent.close()

    def enterEvent(self,ev):
        self.backgroundColor.setRgb(242,146,52) 
        self.update()
        
    def leaveEvent(self,ev):
        self.backgroundColor.setRgb(157,157,157)
        self.update()
示例#16
0
    def __print(self, printer):
        """
        Private slot to the actual printing.
        
        @param printer reference to the printer object (QPrinter)
        """
        p = QPainter(printer)
        marginX = (printer.pageRect().x() - printer.paperRect().x()) // 2
        marginY = (printer.pageRect().y() - printer.paperRect().y()) // 2

        # double the margin on bottom of page
        if printer.orientation() == QPrinter.Portrait:
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 3
        else:
            marginX *= 2
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 2
        if qVersion() >= "5.0.0":
            img = self.mainWidget.grab().toImage()
        else:
            img = QPixmap.grabWidget(self.mainWidget).toImage()
        self.__updateChildren(self.lastStyle)
        p.drawImage(marginX, marginY,
                    img.scaled(width, height,
                               Qt.KeepAspectRatio, Qt.SmoothTransformation))
        p.end()
示例#17
0
 def paintEvent(self, event):
     _size = self.size() - QSize(2, 2)
     if (_size.isEmpty()):
         return
     origX = (_size.width() - self.mNewSize.width() * self.mScale) / 2 + 0.5
     origY = (_size.height() - self.mNewSize.height() * self.mScale) / 2 + 0.5
     oldRect = QRect(self.mOffset, self.mOldSize)
     painter = QPainter(self)
     painter.translate(origX, origY)
     painter.scale(self.mScale, self.mScale)
     pen = QPen(Qt.black)
     pen.setCosmetic(True)
     painter.setPen(pen)
     painter.drawRect(QRect(QPoint(0, 0), self.mNewSize))
     pen.setColor(Qt.white)
     painter.setPen(pen)
     painter.setBrush(Qt.white)
     painter.setOpacity(0.5)
     painter.drawRect(oldRect)
     pen.setColor(Qt.black)
     pen.setStyle(Qt.DashLine)
     painter.setOpacity(1.0)
     painter.setBrush(Qt.NoBrush)
     painter.setPen(pen)
     painter.drawRect(oldRect)
     painter.end()
示例#18
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()
示例#19
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
示例#20
0
    def renderToTexture(self, levelOfDetail = 1.0):
        # Determine the fbo size we will need.
        size = (self.sceneRect().size() * levelOfDetail).toSize()
        fboSize = nextPowerOfTwo(size)
        if fboSize.isEmpty():
            fboSize = QSize(16, 16)

        # Create or re-create the fbo.
        if self.fbo is None or self.fbo.size() != fboSize:
            #del self.fbo
            self.fbo = QGLFramebufferObject(fboSize, self.format)
            if not self.fbo.isValid():
                #del self.fbo
                self.fbo = None
                return 0
            self.dirty = True

        # Return the previous texture contents if the scene hasn't changed.
        if self.fbo is not None and not self.dirty:
            return self.fbo.texture()

        # Render the scene into the fbo, scaling the QPainter's view
        # transform up to the power-of-two fbo size.
        painter = QPainter(self.fbo)
        painter.setWindow(0, 0, size.width(), size.height())
        painter.setViewport(0, 0, fboSize.width(), fboSize.height())
        self.render(painter)
        painter.end()
        self.dirty = False
        return self.fbo.texture()
示例#21
0
    def mouseMoveEvent(self, event):
        if QLineF(QPointF(event.screenPos()), QPointF(event.buttonDownScreenPos(Qt.LeftButton))).length() < QApplication.startDragDistance():
            return

        drag = QDrag(event.widget())
        mime = QMimeData()
        drag.setMimeData(mime)

        ColorItem.n += 1
        if ColorItem.n > 2 and qrand() % 3 == 0:
            image = QImage(':/images/head.png')
            mime.setImageData(image)
            drag.setPixmap(QPixmap.fromImage(image).scaled(30,40))
            drag.setHotSpot(QPoint(15, 30))
        else:
            mime.setColorData(self.color)
            mime.setText("#%02x%02x%02x" % (self.color.red(), self.color.green(), self.color.blue()))

            pixmap = QPixmap(34, 34)
            pixmap.fill(Qt.white)

            painter = QPainter(pixmap)
            painter.translate(15, 15)
            painter.setRenderHint(QPainter.Antialiasing)
            self.paint(painter, None, None)
            painter.end()

            pixmap.setMask(pixmap.createHeuristicMask())

            drag.setPixmap(pixmap)
            drag.setHotSpot(QPoint(15, 20))

        drag.exec_()
        self.setCursor(Qt.OpenHandCursor)
示例#22
0
def getCombinedIcon(keys, cache=pixCache):
    """
    Module function to retrieve a symbolic link icon.

    @param keys list of names of icons (string)
    @param cache reference to the pixmap cache object (PixmapCache)
    @return the requested icon (QIcon)
    """
    height = width = 0
    pixmaps = []
    for key in keys:
        pix = cache.getPixmap(key)
        if not pix.isNull():
            height = max(height, pix.height())
            width = max(width, pix.width())
            pixmaps.append(pix)
    if pixmaps:
        pix = QPixmap(len(pixmaps) * width, height)
        pix.fill(Qt.transparent)
        painter = QPainter(pix)
        x = 0
        for pixmap in pixmaps:
            painter.drawPixmap(x, 0, pixmap.scaled(QSize(width, height)))
            x += width
        painter.end()
        icon = QIcon(pix)
    else:
        icon = QIcon()
    return icon
示例#23
0
 def paintEvent(self, e):
   
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHints(QPainter.Antialiasing, True)
     self.doDrawing(qp)        
     qp.end()
示例#24
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
 def saveChanges(self):
     newImage = QImage(self.image.size(), QImage.Format_ARGB32_Premultiplied)
     painter = QPainter(newImage)
     painter.drawImage(0,0, self.image)
     painter.drawImage(0,0, self.foreground)
     painter.end()
     return newImage
示例#26
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
示例#27
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()
示例#28
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
示例#29
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()
示例#30
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()
示例#31
0
 def paintEvent(self, e):
     qp = QPainter()
     qp.begin(self)
     self.drawLines(qp)
     qp.end()
示例#32
0
    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawWidget(qp)
        qp.end()
示例#33
0
 def paintEvent(self, event):
     if self.do_paint:
         qp = QPainter()
         qp.begin(self)
         self.draw_flag(qp)
         qp.end()
示例#34
0
 def paintEvent(self, event):
     if self.st:
         qp = QPainter()
         qp.begin(self)
         self.circle(qp)
         qp.end()
示例#35
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     if self.can_paint:
         self.draw(qp)
     qp.end()
示例#36
0
def draw_icon(icon, rect, painter, icon_mode, shadow=False):
    cache = icon.pixmap(rect.size())
    dip_offset = QPoint(1, -2)

    cache = QPixmap()
    pixname = "icon {0} {1} {2}".format(icon.cacheKey(), icon_mode,
                                        rect.height())
    if QPixmapCache.find(pixname) is None:
        pix = icon.pixmap(rect.size())
        device_pixel_ratio = pix.devicePixelRatio()
        radius = 3 * device_pixel_ratio
        offset = dip_offset * device_pixel_ratio
        cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2))
        cache.fill(Qt.transparent)

        cache_painter = QPainter(cache)

        if icon_mode == QIcon.Disabled:
            im = pix.toImage().convertToFormat(QImage.Format_ARGB32)
            for y in range(0, im.height()):
                scanline = im.scanLine(y)
                for x in range(0, im.width()):
                    pixel = scanline
                    intensity = qGray(pixel)
                    scanline = qRgba(intensity, intensity, intensity,
                                     qAlpha(pixel))
                    scanline += 1
            pix = QPixmap.fromImage(im)

        # Draw shadow
        tmp = QImage(pix.size() + QSize(radius * 2, radius * 2),
                     QImage.Format_ARGB32_Premultiplied)
        tmp.fill(Qt.transparent)

        tmp_painter = QPainter(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_Source)
        tmp_painter.drawPixmap(
            QRect(radius, radius, pix.width(), pix.height()), pix)
        tmp_painter.end()

        # Blur the alpha channel
        blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied)
        blur_painter = QPainter(blurred)
        blur_painter.end()

        tmp_painter.begin(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150))
        tmp_painter.end()

        tmp_painter.begin(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150))
        tmp_painter.end()

        # Draw the blurred drop shadow
        cache_painter.drawImage(
            QRect(0, 0,
                  cache.rect().width(),
                  cache.rect().height()), tmp)
        # Draw the actual pixmap
        cache_painter.drawPixmap(
            QRect(
                QPoint(radius, radius) + offset,
                QSize(pix.width(), pix.height())), pix)
        cache_painter.end()
        cache.setDevicePixelRatio(device_pixel_ratio)
        QPixmapCache.insert(pixname, cache)

    target_rect = cache.rect()
    target_rect.setSize(target_rect.size() / cache.devicePixelRatio())
    target_rect.moveCenter(rect.center() - dip_offset)
    painter.drawPixmap(target_rect, cache)
 def paintEvent(self, event):
     p = QPainter()
     p.begin(self.viewport())
     p.drawPixmap(0, 0, self.pixmap)
     p.drawPixmap(0, 0, self.pixmapHandwriting)
     p.end()
示例#38
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.draw_rect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(Qt.blue)
            end = QPoint(yAxis + curveScale,
                         xAxis - curveScale * curve.valueForProgress(1))
            painter.draw_rect(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()
示例#39
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_logan_2.clicked.connect(self.logan_clicked)
        self.ui.lbl_phantom.mousePressEvent = self.getPixel
        self.ui.lbl_phantom.mouseDoubleClickEvent = self.draw_curve
        self.ui.lbl_phantom.mouseMoveEvent = self.brightness_control
        self.ui.btn_browse_2.clicked.connect(self.browse_clicked)
        self.ui.kspace.clicked.connect(self.generate_kspace)
        self.ui.pushButton.clicked.connect(self.image_of_Kspace)
        self.ui.pushButton.setEnabled(False)
        self.result = ''
        self.ratio = ""
        self.size = ""
        self.phantom_array = ""
        self.t1_array = ""
        self.t2_array = ""
        self.pd_array = ""
        self.ratio_cont = ""
        self.xx = ""
        self.yy = ""
        self.i = ""
        self.i = 1
        self.br = ""
        self.j = ""
        self.j = 1
        self.ks_image = ""
        self.aaa = ""

    def draw_curve(self, event):
        x = event.pos().x()
        label_width = self.ui.lbl_phantom.width()
        y = event.pos().y()
        label_hight = self.ui.lbl_phantom.height()
        get_x = int((x / label_width) * self.size)
        get_y = int((y / label_hight) * self.size)
        t1 = self.t1_array[get_x][get_y]
        t2 = self.t2_array[get_x][get_y]
        unitVector = [[0], [0], [1]]
        theta = 90
        alpha = 10
        delta_t = 500
        x_curve, y_curve, z_curve = self.draw_curves(unitVector, delta_t, t1,
                                                     t2, theta, alpha)

        self.ui.graphicsView_2.plot(x_curve)
        self.ui.graphicsView_3.plot(y_curve)
        img = self.draw(get_x, get_y, self.aaa)
        self.ui.lbl_phantom.setPixmap(img)

    def getPixel(self, event):
        #        x=self.ui.lbl_phantom.height()
        self.xx = event.pos().x()
        self.yy = event.pos().y()

    def brightness_control(self, event):
        #        x=self.ui.lbl_phantom.height()
        x = event.pos().x()
        y = event.pos().y()
        if self.xx in range(x - 10, x + 10) and self.yy > y:
            self.i = self.i + self.br
        elif self.xx in range(x - 10, x + 10) and self.yy < y:
            self.i = self.i - self.br
        elif self.yy in range(y - 10, y + 10) and self.xx > x:
            self.j = self.j + 10
        elif self.yy in range(y - 10, y + 10) and self.xx < x:
            self.j = self.j - 10
        print(self.i)
        self.ratio = self.i
        self.ratio_cont = self.j
        array_phantom = self.phantom_array
        self.aaa = self.adding_image_to_lbl(array_phantom, 1)
        self.ui.lbl_phantom.setPixmap(self.aaa)

    def browse_clicked(self):
        fileName, _filter = QFileDialog.getOpenFileName(
            self, "Open file", "", "Image files (*.bmp *.png *.gif *.jpg)")
        self.path = fileName
        if fileName:

            self.ui.graphicsView_2.clear()
            self.ui.graphicsView_3.clear()
            self.ui.pushButton.setEnabled(False)
            self.br = .1
            self.ratio = self.i = 1
            self.ratio_cont = self.j = 1
            array = self.convert_image_to_array(fileName)
            self.size = len(array)
            self.phantom_choose(self.size, fileName)

    def logan_clicked(self):

        self.ui.graphicsView_2.clear()
        self.ui.graphicsView_3.clear()
        self.ui.pushButton.setEnabled(False)
        self.ratio = self.i = 1
        self.ratio_cont = self.j = 1

        if self.ui.CBox_size_2.currentText() == "20*20":
            self.size = 20
            p = self.phantom(n=20)
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom20.jpg")
            path = "phantom20.png"
            self.br = .01

        elif self.ui.CBox_size_2.currentText() == "32*32":
            self.size = 32
            p = self.phantom(n=32)
            p = (p) * 200
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom32.jbg")
            path = "phantom32.png"
            self.br = .02

        if self.ui.CBox_size_2.currentText() == "64*64":
            self.size = 64
            p = self.phantom(n=64)
            p = (p) * 200
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom64.jpg")
            path = "phantom64.png"
            self.br = .03

        elif self.ui.CBox_size_2.currentText() == "128*128":
            self.size = 128
            p = self.phantom(n=128)
            p = (p) * 200
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom128.jpg")
            path = "phantom128.png"
            self.br = .05
        elif self.ui.CBox_size_2.currentText() == "256*256":
            self.size = 256
            p = self.phantom(n=256)
            #p=(p)*200
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom256.jpg")
            path = "phantom256.png"
            self.br = .1
        elif self.ui.CBox_size_2.currentText() == "512*512":
            self.size = 512
            p = self.phantom(n=512)
            #p=(p)*200
            mostafa = qimage2ndarray.array2qimage(np.absolute(p))
            mostafa.save("phantom512.jpg")
            path = "phantom256.png"
            self.br = .2

        self.phantom_choose(self.size, path)

    def phantom_choose(self, lbl_size, path):
        array = self.convert_image_to_array(path)
        self.phantom_array, self.t1_array, self.t2_array = self.genrate_total_phantom(
            array)
#        while 1:
#            self.ratio=self.i
#            self.ratio_cont=self.j
#
#            if self.ui.comboBox_2.currentText()== "phantom" :
#                array_phantom=self.phantom_array
#                aaa=self.adding_image_to_lbl(array_phantom , self.ratio)
#                self.ui.lbl_phantom.setPixmap(aaa)
#
#
#
#            elif self.ui.comboBox_2.currentText()== "T1 effect" :
#                array_t1=self.t1_array
#                aaa=self.adding_image_to_lbl(array_t1 , self.ratio)
#                self.ui.lbl_phantom.setPixmap(aaa)
#            elif self.ui.comboBox_2.currentText()== "T2 effect" :
#                array_t2=self.t2_array
#                aaa=self.adding_image_to_lbl(array_t2 , self.ratio)
#                self.ui.lbl_phantom.setPixmap(aaa)
#            QApplication.processEvents()

#    def Set_T1(self,phantom_array):
#        t1_array=np.ones((self.size,self.size))
#        t2_array=np.ones((self.size,self.size))
#        phantom=np.ones((self.size,self.size))
#        Max_value= np.max (phantom_array)
#        Min_Value= np.min (phantom_array)
#        for x in range(0,self.size):
#            for y in range(0,self.size):
#                if (phantom_array[x][y] ==Max_value) :
#                    t1_array[x][y]=1090
#                    t2_array[x][y]=1
#                    phantom[x][y]=phantom_array[x][y]
#                else:
#                    if (phantom_array[x][y]==Min_Value):
#                        t1_array[x][y]=1
#                        t2_array[x][y]=1090
#                        phantom[x][y]=phantom_array[x][y]
#
#
#                    else:
#                        t1_array[x][y]=int(1+(phantom_array[x][y]*1090)/Max_value)
#                        t2_array[x][y]=int(1090-(phantom_array[x][y]*1090)/Max_value)
#                        phantom[x][y]=phantom_array[x][y]
#
#        return phantom,t1_array , t2_array

    def genrate_total_phantom(self, phantom_array):
        t1_array = np.ones((self.size, self.size))
        t2_array = np.ones((self.size, self.size))
        #pd_array = np.ones((self.size,self.size))
        phantom_arrray = np.ones((self.size, self.size))
        for i in range(0, self.size):
            for j in range(0, self.size):
                if phantom_array[i][j] < 255 and phantom_array[i][j] > 80:
                    phantom_arrray[i][j] = phantom_array[i][j]
                    t1_array[i][j] = np.abs(
                        int(1 + (phantom_array[i][j] * (2))))
                    t2_array[i][j] = np.abs(1 + (256 - t1_array[i][j]))
                    #pd_array[i][j]=0
                elif phantom_array[i][j] < 100 and phantom_array[i][j] > 20:
                    phantom_arrray[i][j] = phantom_array[i][j]
                    t1_array[i][j] = np.abs(int(1 + (phantom_array[i][j] * 3)))
                    t2_array[i][j] = np.abs(1 + (256 - t1_array[i][j]))
                    #pd_array[i][j]=100

                else:
                    phantom_arrray[i][j] = phantom_array[i][j]
                    t1_array[i][j] = 60 + (phantom_array[i][j])
                    t2_array[i][j] = 40 + (phantom_array[i][j])
                    #pd_array[i][j]=200
            QApplication.processEvents()
            aaa = self.adding_image_to_lbl(phantom_arrray, self.ratio)
            self.ui.lbl_phantom.setPixmap(aaa)

        return phantom_array, t1_array, t2_array

    def convert_image_to_array(self, path):
        img = Image.open(path).convert('L')
        img_array = np.asarray(img)
        return img_array

    def adding_image_to_lbl(self, aarray, bright_ratio):
        mostafa = qimage2ndarray.array2qimage(np.absolute(aarray))
        mostafa.save("output1.jpg")
        im = Image.open("output1.jpg")
        xxxx = self.change_contrast(im, self.ratio_cont)
        enhanced_im = self.change_brightness(xxxx, self.ratio)
        enhanced_im.save("enhanced.sample5.png")
        pixmap = QPixmap("enhanced.sample5.png")
        pixmap = pixmap.scaled(int(pixmap.height()), int(pixmap.width()),
                               QtCore.Qt.KeepAspectRatio)
        self.pixmap = pixmap
        return self.pixmap

    def change_contrast(self, img, level):
        factor = (259 * (level + 255)) / (255 * (259 - level))

        def contrast(c):
            value = 128 + factor * (c - 128)
            return max(0, min(255, value))

        return img.point(contrast)

    def change_brightness(self, img, level):
        enhancer = ImageEnhance.Brightness(img)
        enhanced_im = enhancer.enhance(level)
        return enhanced_im

    def draw_curves(self, unitVector, delta, t1, t2, theta, alpha):
        x_curve = []
        y_curve = []
        z_curve = []
        theta = ((theta * 22 / 7) / 180)
        rotationx = [[1, 0, 0], [0, np.cos(theta),
                                 np.sin(theta)],
                     [0, -np.sin(theta), np.cos(theta)]]
        rotationxy = [[np.cos(alpha), -np.sin(alpha), 0],
                      [-(np.sin(alpha)), np.cos(alpha), 0], [0, 0, 1]]
        for delta_t in range(delta):
            decayRecoveryArray = [[np.exp(-delta_t / t2), 0, 0],
                                  [0, np.exp(-delta_t / t2), 0],
                                  [0, 0, np.exp(-delta_t / t1)]]
            finaldrArray = [[0], [0], [(1 - (np.exp(-delta_t / t1)))]]
            rotatedVector = np.matmul(rotationx, unitVector)
            rotatedVector = np.matmul(rotationxy, rotatedVector)
            rotatedVector = np.matmul(decayRecoveryArray, rotatedVector)
            rotatedVector = finaldrArray + rotatedVector
            x_curve.extend(rotatedVector[0])
            y_curve.extend(rotatedVector[1])
            z_curve.extend(rotatedVector[2])
        return x_curve, y_curve, z_curve

    def generate_kspace(self):
        self.ui.lbl_kspace.clear()
        unitVector = [[0], [0], [1]]
        theta = self.ui.SP_theta.value()
        tr = self.ui.SP_TE.value()
        te = self.ui.SP_TR.value()
        k_space, self.ks_image = self.creare_Kspace(unitVector, te, tr, theta)
        aaa = self.adding_image_to_lbl(k_space, 1)
        self.ui.lbl_kspace.setPixmap(aaa)

    def creare_Kspace(self, unitVector, te, tr, theta):

        t2 = ((self.t1_array) + 1000)
        t1 = (self.t2_array + 10)

        k_space = np.zeros((self.size, self.size), dtype=np.complex)
        print('theta= ', theta)

        signal = np.ones((self.size, self.size))
        signal = signal * np.sin(theta * np.pi / 180.)

        for kspacerow in range(self.size):

            signal = signal * np.exp(-te / t2)

            for kspacecol in range(self.size):
                GX = 2 * np.pi * kspacerow / self.size
                GY = 2 * np.pi * kspacecol / self.size

                for i in range(self.size):
                    for j in range(self.size):
                        total_theta = (GX * i + GY * j)
                        k_space[kspacerow, kspacecol] += signal[i, j] * np.exp(
                            -1j * total_theta)
                        QApplication.processEvents()

            signal = 1 - np.exp(-tr / t1)


#            signal = np.ones((self.size,self.size))
#            signal = signal * np.sin(theta * np.pi / 180. )
        K_S = k_space
        maxi = np.max(K_S)
        mini = np.min(K_S)
        K_S = ((K_S - mini)) * (255 / (maxi - mini))

        test1 = np.absolute(np.fft.ifft2(k_space))
        maxi = np.max(test1)
        mini = np.min(test1)
        test1 = ((test1 - mini)) * (255 / (maxi - mini))
        self.ui.pushButton.setEnabled(True)
        return K_S, test1

    def image_of_Kspace(self):
        aaa = self.adding_image_to_lbl(self.ks_image, 1)
        self.ui.lbl_kspace.setPixmap(aaa)

    def phantom(self, n=100, p_type='Modified Shepp-Logan', ellipses=None):
        if (ellipses is None):
            ellipses = self._select_phantom(p_type)
        elif (np.size(ellipses, 1) != 6):
            raise AssertionError("Wrong number of columns in user phantom")

        # Blank image
        p = np.zeros((n, n))

        # Create the pixel grid
        ygrid, xgrid = np.mgrid[-1:1:(1j * n), -1:1:(1j * n)]

        for ellip in ellipses:
            I = ellip[0]
            a2 = ellip[1]**2
            b2 = ellip[2]**2
            x0 = ellip[3]
            y0 = ellip[4]
            phi = ellip[5] * np.pi / 180  # Rotation angle in radians

            # Create the offset x and y values for the grid
            x = xgrid - x0
            y = ygrid - y0

            cos_p = np.cos(phi)
            sin_p = np.sin(phi)

            # Find the pixels within the ellipse
            locs = (((x * cos_p + y * sin_p)**2) / a2 +
                    ((y * cos_p - x * sin_p)**2) / b2) <= 1

            # Add the ellipse intensity to those pixels
            p[locs] += I

        return p

    def _select_phantom(self, name):
        if (name.lower() == 'modified shepp-logan'):
            e = self._mod_shepp_logan()
        else:
            raise ValueError("Unknown phantom type: %s" % name)

        return e

    def _mod_shepp_logan(self):
        #  Modified version of Shepp & Logan's head phantom,
        #  adjusted to improve contrast.  Taken from Toft.
        return [[1, .69, .92, 0, 0, 0], [-.80, .6624, .8740, 0, -.0184, 0],
                [-.20, .1100, .3100, .22, 0, -18],
                [-.20, .1600, .4100, -.22, 0, 18],
                [.10, .2100, .2500, 0, .35, 0], [.10, .0460, .0460, 0, .1, 0],
                [.10, .0460, .0460, 0, -.1, 0],
                [.10, .0460, .0230, -.08, -.605, 0],
                [.10, .0230, .0230, 0, -.606, 0],
                [.10, .0230, .0460, .06, -.605, 0]]

    def draw(self, x, y, fullImage):
        #fullImage = QPixmap(self.myPath)
        self.painterInstance = QPainter(fullImage)
        self.painterInstance.begin(self)
        self.penRectangle = QPen(QtCore.Qt.red)
        self.penRectangle.setWidth(1)
        #self.penPoint = QPen(QtCore.Qt.black)
        #self.penPoint.setWidth(1)
        #self.painterInstance.setPen(self.penPoint)
        #self.painterInstance.drawRect(x,y,1,1)
        self.painterInstance.setPen(self.penRectangle)
        self.painterInstance.drawRect(x - 0, y - 0, 1, 1)
        self.painterInstance.end()
        #result = fullImage.scaled(self.ui.lbl_phantom.width(),self.ui.lbl_phantom.height())
        #result.save('alllllla.png')
        #self.ui.lbl_phantom.setPixmap(fullImage)
        self.painterInstance.end()
        return (fullImage)
示例#40
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     qp.drawLine(self.pos1[0], self.pos1[1], self.pos2[0], self.pos2[1])
     qp.end()
 def paintEvent(self, event):
     paint = QPainter()
     paint.begin(self)
     self.drawRandomPoint(paint)
     paint.end()
示例#42
0
    def paintEvent(self, event):

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

        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()
示例#44
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     self.drawFlag(qp)
     qp.end()
示例#45
0
    def save_as_pdf(self):
        filename = QFileDialog.getSaveFileName(self, 'Save to PDF', 'c:\\',
                                               "*.pdf")

        if filename != ('', ''):
            if os.path.exists(filename[0]):
                try:
                    infile = PdfFileReader(filename[0], 'rb')
                except:
                    error = QMessageBox()
                    error.setIcon(QMessageBox.Warning)
                    error.setStandardButtons(QMessageBox.Ok)
                    error.setText(
                        "File could not be written to. If the file is currently open, try closing it"
                    )
                    error.exec_()
                    return
                if infile.getNumPages() == 0:
                    print("HERE!")
                    doc = QTextDocument()
                    doc.print(printer)

            printer = QPrinter()
            printer.setPageSize(QPrinter.A4)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(filename[0])

            painter = QPainter()

            font = QFont("times")
            font.setPointSize(12)

            x = painter.begin(printer)
            if x == False:
                error = QMessageBox()
                error.setIcon(QMessageBox.Warning)
                error.setStandardButtons(QMessageBox.Ok)
                error.setText(
                    "File could not be saved. If the file is currently open, try closing it"
                )
                error.exec_()
                return
            painter.setFont(font)

            for i in range(0, self.symbol_tests.count()):
                cur_symbol_test = self.symbol_tests.widget(i)

                if cur_symbol_test.print_visual_context() == False:
                    pixmap = cur_symbol_test.get_symbol()
                    pixmap = pixmap.scaled(350, 350)

                    painter.drawPixmap(30, 100, pixmap)
                    painter.drawText(750, 20, cur_symbol_test.get_page())
                    painter.drawText(
                        420, 200, 350, 400, QtCore.Qt.TextWordWrap,
                        "Context: " + cur_symbol_test.get_context())
                    painter.drawText(30, 600, cur_symbol_test.get_question1())
                    painter.drawText(30, 830, cur_symbol_test.get_question2())

                    cur_pen = painter.pen()
                    line_pen = QPen()
                    line_pen.setWidth(2)
                    painter.setPen(line_pen)
                    painter.drawLine(70, 656, 600, 656)
                    painter.drawLine(70, 712, 600, 712)
                    painter.drawLine(70, 768, 600, 768)

                    painter.drawLine(70, 886, 600, 886)
                    painter.drawLine(70, 942, 600, 942)
                    painter.drawLine(70, 998, 600, 998)
                    painter.setPen(cur_pen)

                else:
                    pixmap = cur_symbol_test.get_visual_context()
                    pixmap = pixmap.scaled(300, 300)

                    painter.drawPixmap(200, 10, pixmap)

                    pixmap = cur_symbol_test.get_symbol()
                    pixmap = pixmap.scaled(250, 250)

                    painter.drawPixmap(225, 320, pixmap)

                    painter.drawText(750, 20, cur_symbol_test.get_page())
                    #painter.drawText(420, 200, 350, 400, QtCore.Qt.TextWordWrap, "Context: " + cur_symbol_test.get_context())
                    painter.drawText(30, 600, cur_symbol_test.get_question1())
                    painter.drawText(30, 830, cur_symbol_test.get_question2())

                    cur_pen = painter.pen()
                    line_pen = QPen()
                    line_pen.setWidth(2)
                    painter.setPen(line_pen)
                    painter.drawLine(70, 656, 600, 656)
                    painter.drawLine(70, 712, 600, 712)
                    painter.drawLine(70, 768, 600, 768)

                    painter.drawLine(70, 886, 600, 886)
                    painter.drawLine(70, 942, 600, 942)
                    painter.drawLine(70, 998, 600, 998)
                    painter.setPen(cur_pen)
                if (i < self.symbol_tests.count() - 1):
                    printer.newPage()

            painter.end()
 def paintEvent(self, event):
     p = QPainter()
     p.begin(self)
     self.draw(p)
     p.end()
示例#47
0
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)
示例#48
0
 def paintEvent(self, event):
     if self.paint:
         qp = QPainter()
         qp.begin(self)
         self.draw(event, qp)
         qp.end()
示例#49
0
 def paintEvent(self, *args, **kwargs):
     b = QPainter()
     b.begin(self)
     self.draw(b)
     b.end()
示例#50
0
    def paintEvent(self, e):
        '''
    Подновляет (рисует) изображение памяти по-пиксельно
    '''
        if self.startAddress == None:
            return

        qp = QPainter()
        qp.begin(self)

        # Подписываем адреса
        qp.setFont(QFont('DejaVu Sans Bold', 10, QFont.Bold))
        rect = QRect(X0, 0, (dX * 7), dY)
        #qp.drawRect(rect)
        addr = (
            (self.startAddress) >> 16) & 0xFFFF  # Берём только цифры ZZZZ....
        txt = "{:04X}".format(addr)
        qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt)

        qp.setFont(QFont('DejaVu Sans', 10))
        for y in range(7):
            rect = QRect(0, (y * dY + Y0), X0, dY)
            #qp.drawRect(rect)
            addr = ((self.startAddress + y * 256) >>
                    8) & 0xFF  # Берём только цифры ....YY..
            txt = "{:02X}xx".format(addr)
            qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt)

        for x in range(7):
            rect = QRect((x * dX + X0), (Y0 - dY), dX, dY)
            #qp.drawRect(rect)
            addr = (self.startAddress +
                    x) & 0xFF  # Берём только цифры ......XX
            txt = "{:02X}".format(addr)
            qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt)

        #qp.setFont(QFont('DejaVu Sans', 10))
        for y in range(7):
            for x in range(7):
                rect = QRect((x * dX + X0), (y * dY + Y0), (dX - 1), (dY - 1))

                if self.content != None:
                    c = self.content[y][x]
                    r = (c >> 5) & 0x07
                    g = (c >> 2) & 0x07
                    b = (c) & 0x03

                    #qp.setPen(QPen(QColor(r, g, b)))
                    color = QColor(r << 5, g << 5, b << 6)
                    qp.fillRect(rect, color)
                    qp.drawRect(rect)

                    bright = r * 28 + g * 61 + b * 11
                    if bright < (656 / 2):
                        qp.setPen(Qt.white)
                    else:
                        qp.setPen(Qt.black)

                    txt = "{:02X}".format(self.content[y][x])
                    qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt)

        #qp.setFont(QFont('DejaVu Sans Bold', 10, QFont.Bold))
        #qp.setPen(QColor("Blue"))
        # qp.drawText(rect, Qt.Alignment((Qt.AlignVCenter | Qt.AlignHCenter)), self.startAddress)

        #qp.setPen(QColor("Black"))

        qp.end()
示例#51
0
class Tetris(QWidget):

    screenWidth = None          # 窗口宽度
    screenHeight = None         # 窗口高度
    isGameStart = None          # 游戏是否开始
    isGameOver = None           # 游戏是否结束
    isPause = None              # 游戏是否暂停
    pauseButton = None          # 暂停游戏按钮
    resumeButton = None         # 继续游戏按钮
    restartButton = None        # 重新开始游戏按钮
    gameOverImage = None        # 游戏结束时显示的图片
    blockSize = None            # 一个方块的大小(像素px)
    allRows = None              # 所有的行
    allColumns = None           # 所有的列
    allBlock = None             # 二维数组, 记录方块
    currentRow = None           # 当前行
    currentColumn = None        # 当前列
    dropTimer = None            # 方块下降的定时器
    updateTimer = None          # 屏幕更新的定时器
    removeBlockTimer = None     # 消除方块的定时器
    dropInterval = None         # 方块下降定时器的时间间隔
    updateInterval = None       # 屏幕更新定时器的时间间隔
    removeBlockInterval = None  # 消除方块定时器的时间间隔
    blocks = None               # 枚举所有的方块
    blockDict = None            # 存储方块属性的字典
    nextBlockDict = None        # 存储下一个方块属性的字典
    block = None                # 当前的方块
    shape = None                # 当前方块的类型
    index = None                # 当前方块类型的下标
    score = None                # 得分情况
    pixmap = None               # 临时存储图片路径
    paint = None                # 画笔
    font = None                 # 字体

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

        self.screenWidth = 900
        self.screenHeight = 800
        self.setFocusPolicy(Qt.StrongFocus)         # 设置焦点, 监听键盘
        self.resize(self.screenWidth, self.screenHeight)

        self.initButton()
        self.initImage()

    def initButton(self):
        """初始化重新开始游戏的按钮"""
        # 暂停游戏按钮
        self.pauseButton = QPushButton(self)
        self.pauseButton.setObjectName('pauseButton')
        self.pauseButton.setShortcut('P')
        self.pauseButton.setToolTip('暂停')  # 悬停在按钮上的提示->暂停
        self.pauseButton.move(self.screenWidth - 210, 5)  # 按钮的位置
        self.pauseButton.hide()  # 默认隐藏
        self.pauseButton.clicked.connect(lambda: {
            self.pause(),
            self.pauseButton.hide(),
            self.resumeButton.show(),
        })

        # 继续游戏按钮
        self.resumeButton = QPushButton(self)
        self.resumeButton.setObjectName('resumeButton')
        self.resumeButton.setToolTip('继续')  # 悬停在按钮上的提示->继续
        self.resumeButton.move(self.screenWidth - 210, 5)  # 按钮的位置
        self.resumeButton.hide()  # 默认隐藏
        self.resumeButton.clicked.connect(lambda: {
            self.resume(),
            self.resumeButton.hide(),
            self.pauseButton.show(),
        })

        # 重新开始游戏按钮
        self.restartButton = QPushButton(self)
        self.restartButton.setObjectName('restartButton')
        self.restartButton.move(self.screenWidth // 2 - 200, self.screenHeight // 2 - 50)
        self.restartButton.hide()       # 默认隐藏
        self.restartButton.clicked.connect(self.gameOver)

    def initImage(self):
        """初始化游戏结束的图片"""
        self.gameOverImage = QLabel(self)
        self.gameOverImage.setPixmap(QPixmap('./icons/game_over.png'))
        self.gameOverImage.move(self.screenWidth // 24, self.screenHeight // 4)
        self.gameOverImage.hide()   # 默认隐藏

    def initSetting(self):
        """初始化方块的一些初始值"""
        self.blocks = {
            'L Shape': [[[0, 0], [0, -1], [0, -2], [1, -2]], [[-1, -1], [0, -1], [1, -1], [-1, -2]],
                        [[-1, 0], [0, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, 0]]],
            'J Shape': [[[0, 0], [0, -1], [0, -2], [-1, -2]], [[-1, 0], [-1, -1], [0, -1], [1, -1]],
                        [[0, 0], [1, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, -2]]],
            'Z Shape': [[[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]],
                        [[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]]],
            'S Shape': [[[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]],
                        [[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]]],
            'O Shape': [[[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]],
                        [[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]]],
            'I Shape': [[[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]],
                        [[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]]],
            'T Shape': [[[-1, -1], [0, -1], [1, -1], [0, -2]], [[0, 0], [-1, -1], [0, -1], [0, -2]],
                        [[0, 0], [-1, -1], [0, -1], [1, -1]], [[0, 0], [0, -1], [1, -1], [0, -2]]]
        }
        self.score = 0
        self.blockSize = 40     # 方块的大小
        self.allRows = 20       # 总共20行
        self.allColumns = 15    # 总共15列
        self.currentRow = self.allRows + 4   # +4行是用来放置待出现的方块的
        self.currentColumn = self.allColumns // 2
        self.allBlock = [[0 for row in range(self.allColumns)] for column in range(self.allRows + 5)]
        self.allBlock[0] = [1 for column in range(self.allColumns)]    # 用来判断方块是否到底
        # print(self.allBlock)

    def initFont(self):
        """初始化字体"""
        # 使用本地字体
        fontID = QFontDatabase.addApplicationFont('./Font/Consolas Italic.ttf')
        self.font = QFont()
        self.font.setFamily(QFontDatabase.applicationFontFamilies(fontID)[0])
        self.font.setItalic(True)   # 斜体
        self.font.setBold(True)     # 粗体
        self.font.setPixelSize(40)  # 字体大小

    def initTimer(self):
        """初始化定时器"""
        # 方块下降的定时器
        self.dropTimer = QTimer(self)
        self.dropInterval = 500     # 每0.5秒下降一格
        self.dropTimer.start(self.dropInterval)
        self.dropTimer.timeout.connect(self.blockDrop)

        # paintEvent更新的定时器
        self.updateTimer = QTimer(self)
        self.updateInterval = 10
        self.updateTimer.start(self.updateInterval)
        self.updateTimer.timeout.connect(self.update)

        # 消除方块的定时器
        self.removeBlockTimer = QTimer(self)
        self.removeBlockInterval = 150
        self.removeBlockTimer.start(self.removeBlockInterval)
        self.removeBlockTimer.timeout.connect(self.removeBlock)

    def getBlock(self):
        """获取方块"""
        shape = random.choice(list(self.blocks.keys()))     # 选择随机方块的类型
        index = random.randint(0, 3)
        # if shape == 'L Shape' and index == 3:
        #     pass
        block = self.blocks[shape][index]
        blockDict = {
            'shape': shape,
            'index': index,
            'block': block,
        }
        return blockDict

    def getCurrentBlock(self):
        """获取目前的方块"""
        self.blockDict = self.nextBlockDict
        self.shape = self.blockDict['shape']
        self.index = self.blockDict['index']
        self.block = self.blockDict['block']
        self.nextBlockDict = self.getBlock()

    def blockDrop(self):
        """每运行一次, 方块下降一格, 通过QTimer每隔一定时间运行一次"""
        for position1 in self.block:
            x = position1[0] + self.currentColumn    # x->column
            y = position1[1] + self.currentRow       # y->row
            # print(x, y)
            if self.allBlock[y - 1][x] == 1:
                for position2 in self.block:
                    self.allBlock[position2[1] + self.currentRow][position2[0] + self.currentColumn] = 1
                break
        else:
            # 下落方块没有接触到其他方块或者没有到底, 继续下降
            self.currentRow -= 1
            return

        # 判断游戏结束
        if 1 in self.allBlock[self.allRows]:
            self.pause()
            self.update()
            self.removeBlockTimer.disconnect()
            self.updateTimer.disconnect()
            self.pauseButton.hide()
            self.gameOverImage.show()
            self.restartButton.show()
            return

        # 方块下落完成, 获取下一个方块
        self.getCurrentBlock()
        self.currentRow = self.allRows + 4
        self.currentColumn = self.allColumns // 2

    def removeBlock(self):
        """消除方块"""
        # 叠满一行时消除方块, 从上往下消除
        for row in range(self.allRows, 0, -1):
            if 0 not in self.allBlock[row]:
                # 消除方块时触发音效, 消除一行触发一次
                player = QMediaPlayer(self)
                player.setMedia(QMediaContent(QUrl.fromLocalFile('./AudioFrequency/dingdong.mp3')))
                player.play()

                self.allBlock.pop(row)  # 即删即增
                self.allBlock.append([0 for column in range(self.allColumns)])
                self.score += 1

                break

    def blockMove(self, movePosition):
        """左右移动方块movePosition>0 代表向右移动一格 <0 代表向左移动一格"""
        for position in self.block:
            x = position[0] + self.currentColumn + movePosition
            y = position[1] + self.currentRow
            if x < 0 or x > self.allColumns - 1 or y > self.allRows:
                # 说明方块左右移动出边界了
                return
            elif self.allBlock[y][x] == 1:
                # 说明方块左右移动碰到方块了
                return
        else:
            self.currentColumn += movePosition

    def rotate(self):
        """顺时针旋转方块"""
        for position in self.blocks[self.shape][(self.index + 1) % 4]:
            x = position[0] + self.currentColumn
            y = position[1] + self.currentRow
            # print(x, y)
            if x < 0 or x > self.allColumns - 1 or y > self.allRows:
                # 说明方块旋转时候出边界了
                return
            elif self.allBlock[y][x] == 1:
                # 说明方块旋转时候碰到方块了
                return
        else:
            self.index += 1
            # print(self.blocks[self.shape][self.index % 4])
            self.block = self.blocks[self.shape][self.index % 4]

    def start(self):
        """开始游戏"""
        self.isGameStart = True
        self.isGameOver = False
        self.isPause = False
        self.pauseButton.show()
        self.initSetting()
        self.initFont()
        self.initTimer()
        self.nextBlockDict = self.getBlock()
        self.getCurrentBlock()

    def pause(self):
        """游戏暂停"""
        self.isPause = True
        self.dropTimer.disconnect()

    def resume(self):
        """游戏继续"""
        self.isPause = False
        self.dropTimer.start(self.dropInterval)
        self.dropTimer.timeout.connect(self.blockDrop)

    def gameOver(self):
        """游戏结束"""
        self.isGameOver = True

    def paintEvent(self, event):
        """重写paintEvent, 使用QTimer, 每10ms调用一次"""
        self.paint = QPainter(self)
        self.paint.begin(self)  # 开始重绘

        if self.isGameStart is True:
            penColor = QColor(255, 255, 255)  # 白色
            # backgroundColor = QColor(255, 192, 203)  # 粉色
            self.paint.setPen(QPen(penColor, 2, Qt.SolidLine, Qt.RoundCap))     # 白色,
            self.pixmap = QPixmap('./icons/game_background.png')
            self.paint.drawPixmap(QRect(0, 0, self.screenWidth, self.screenHeight), self.pixmap)    # 背景图片
            self.paint.drawLine(self.screenWidth - 300, 0, self.screenWidth - 300, self.screenHeight)   # 分割线

            # 绘制正在下落的方块
            for position in self.block:
                x = position[0] + self.currentColumn
                y = position[1] + self.currentRow
                self.paint.drawPixmap(QRect(x * self.blockSize, (self.allRows - y) * self.blockSize,
                                            self.blockSize, self.blockSize), QPixmap('./icons/block.png'))

            # 绘制静态方块
            for row in range(1, self.allRows + 1):
                for column in range(self.allColumns):
                    if self.allBlock[row][column] == 1:
                        self.paint.drawPixmap(QRect(column * self.blockSize, (self.allRows - row) * self.blockSize,
                                                    self.blockSize, self.blockSize), QPixmap('./icons/fill_block.png'))

            # 绘制下一个出现的方块
            for position in self.nextBlockDict['block']:
                x = position[0] + 18.5  # 18.5是740px/40px(方块大小)
                y = position[1] + 12.5   # 7.5是500px/40px(方块大小) 从下往上
                self.paint.drawPixmap(QRect(int(x * self.blockSize), int((self.allRows - y) * self.blockSize),
                                            self.blockSize, self.blockSize), QPixmap('./icons/block.png'))

            # 绘制得分情况
            self.paint.setFont(self.font)
            self.paint.drawText(self.screenWidth - 250, 150, 'Score: %d' % self.score)

        self.paint.end()    # 结束重绘

    def keyPressEvent(self, event):
        """重写keyPressEvent"""
        if self.isGameOver is False and self.isPause is False:
            if event.key() == Qt.Key_A:
                self.blockMove(-1)
            elif event.key() == Qt.Key_D:
                self.blockMove(1)
            if event.key() == Qt.Key_W:
                self.rotate()
            if event.key() == Qt.Key_S:
                # 加速下降, 加速一个方格
                self.blockDrop()
示例#52
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     qp.drawText(event.rect(), Qt.AlignCenter, 'Boilerplate Code')
     qp.end()
示例#53
0
 def paintEvent(self, event):
     ap = QPainter()
     ap.begin(self)
     self.drawPoints(event, ap)
     ap.end()
示例#54
0
class Canvas(QWidget):
    def __init__(self, parent, w, h, offset_x, offset_y, bg, engine):
        super().__init__()
        self.w = w
        self.h = h
        self.engine = engine
        self.parent = parent
        self.cam = engine.cam
        self.cx, self.cy = w // 2, h // 2
        self.pos = (offset_x, offset_y)
        self.mouse_pressed = False
        self.lines = [((0, 0), (0, w)), ((0, w), (w, h)), ((w, h), (0, h)),
                      ((0, h), (0, 0))]

        self.setFixedSize(w, h)
        self.setParent(parent)
        self.setStyleSheet('background-color: {}'.format(bg))
        self.move(offset_x, offset_y)
        self.setMouseTracking(True)
        self.show()

        self.border_brush = QPen(Qt.black, int(w / 200), Qt.SolidLine)
        self.verts_brush = QPen(Qt.black, int(w / 70), Qt.SolidLine)

    def mousePressEvent(self, event):
        self.setFocus()
        self.parent.selector.hide()
        self.parent.move_window.hide()
        self.parent.scale_window.hide()
        self.parent.rotate_window.hide()
        if event.button() == Qt.LeftButton:
            self.mouse_pressed = True
            self.parent.pointer.click(event.x(), event.y())

    def mouseReleaseEvent(self, event):
        self.mouse_pressed = False

    def mouseMoveEvent(self, event):
        if self.mouse_pressed:
            self.parent.pointer.update_position(event.x(), event.y())

    def paintEvent(self, event):
        self.painter = QPainter(self)

        for i in self.engine.figures:
            figure = self.engine.figures[i]
            self.draw_figure(figure)
        self.painter.end()
        # pygame.draw.line(screen, clrs.black, points[0], points[1], 1)

    def draw_figure(self, figure):
        for edge in figure.edges:
            points = []
            for x, y, z in (figure.vertices[edge[0]],
                            figure.vertices[edge[1]]):
                if self.cam.mode == 0:
                    x -= self.cam.pos[0]
                    y -= self.cam.pos[1]
                    z -= self.cam.pos[2]

                    x, y = Engine.rotate2d((x, y), -self.cam.rot[1])
                    z, y = Engine.rotate2d((z, y), self.cam.rot[0])
                else:
                    x, y, z = Engine.rotate_vert((x, y, z), self.cam.rot[0], 0,
                                                 self.cam.rot[1])
                    x -= self.cam.pos[0]
                    y -= self.cam.pos[1]
                    z -= self.cam.pos[2]

                if y > -0.01:
                    y = 0.01
                f = -300 / abs(y)
                x, y = x * f, z * f
                points += [(self.cx - x, self.cy + y)]
                self.painter.setPen(self.verts_brush)
                if self.is_point_inside((self.cx - x, self.cy + y)):
                    self.painter.drawPoint(self.cx - x, self.cy + y)

            self.painter.setPen(self.border_brush)
            self.painter.drawLine(points[0][0], points[0][1], points[1][0],
                                  points[1][1])

    def is_point_inside(self, p):
        return p[0] >= 0 and p[0] < self.w and p[1] >= 0 and p[1] < self.h
示例#55
0
    def paintEvent(self, event):
        self.gt = GetGCPGeoTransform()  # TODO : Here?
        painter = QPainter(self)

        if (self.surface.isActive()):
            videoRect = self.surface.videoRect()
            if not videoRect.contains(event.rect()):
                region = event.region()
                region.subtracted(QRegion(videoRect))
                brush = self.palette().window()
                for rect in region.rects():
                    painter.fillRect(rect, brush)

            try:
                self.surface.paint(painter)
            except:
                None
        else:
            painter.fillRect(event.rect(), self.palette().window())
        try:
            SetImageSize(self.surface.currentFrame.width(),
                         self.surface.currentFrame.height())
        except:
            None

        # Magnifier Glass
        if self.zoomed and magnifier:
            dim = min(self.width(), self.height())
            magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3)
            radius = magnifierSize / 2
            ring = radius - 15
            box = QSize(magnifierSize, magnifierSize)

            # reupdate our mask
            if self.maskPixmap.size() != box:
                self.maskPixmap = QPixmap(box)
                self.maskPixmap.fill(Qt.transparent)
                g = QRadialGradient()
                g.setCenter(radius, radius)
                g.setFocalPoint(radius, radius)
                g.setRadius(radius)
                g.setColorAt(1.0, QColor(64, 64, 64, 0))
                g.setColorAt(0.5, QColor(0, 0, 0, 255))
                mask = QPainter(self.maskPixmap)
                mask.setRenderHint(QPainter.Antialiasing)
                mask.setCompositionMode(QPainter.CompositionMode_Source)
                mask.setBrush(g)
                mask.setPen(Qt.NoPen)
                mask.drawRect(self.maskPixmap.rect())
                mask.setBrush(QColor(Qt.transparent))
                mask.drawEllipse(g.center(), ring, ring)
                mask.end()

            center = self.dragPos - QPoint(0, radius)
            center += QPoint(0, radius / 2)
            corner = center - QPoint(radius, radius)
            xy = center * 2 - QPoint(radius, radius)
            # only set the dimension to the magnified portion
            if self.zoomPixmap.size() != box:
                self.zoomPixmap = QPixmap(box)
                self.zoomPixmap.fill(Qt.lightGray)

            if True:
                painter = QPainter(self.zoomPixmap)
                painter.translate(-xy)
                self.largePixmap = QPixmap.fromImage(self.surface.image)
                painter.drawPixmap(self.offset * 2, self.largePixmap)
                painter.end()

            clipPath = QPainterPath()
            clipPath.addEllipse(QPointF(center), ring, ring)
            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing)
            painter.setClipPath(clipPath)
            painter.drawPixmap(corner, self.zoomPixmap)
            # painter.setClipping(False)
            painter.drawPixmap(corner, self.maskPixmap)
            painter.setPen(Qt.gray)
            painter.drawPath(clipPath)
示例#56
0
 def paintEvent(self, event):  # 画出指示箭头
     qp = QPainter()
     qp.begin(self)
     self.drawLines(qp)
     qp.end()
示例#57
0
    def paintEvent(self, event):
        unscaledWidth = self.cellPixmapUnscaled.width()
        unscaledHeight = self.cellPixmapUnscaled.height()

        painter = QPainter()

        #get unscaled pixmap without green rectangles
        self.cellPixmap = self.cellPixmapUnscaled.copy()
        #draw rectangles
        painter.begin(self.cellPixmap)
        if self.isDrawingRect:
            painter.setBrush(QColor(0, 255, 0, 100))
            halfRFS = self.recFieldSize // 2
            for point in self.pointsArray:
                painter.drawRect(point.x - halfRFS, point.y - halfRFS,
                                 self.recFieldSize, self.recFieldSize)
            # self.isDrawingRect = True

        painter.end()

        self.cellPixmap = self.cellPixmap.scaled(self.xScaled * unscaledWidth,
                                                 self.xScaled * unscaledHeight,
                                                 Qt.KeepAspectRatioByExpanding)

        #self.pixmapHolder = self.pixmapHolder.scaled(self.imageWidth, self.imageHeight)
        self.pixmapHolder = QPixmap(self.imageWidth, self.imageHeight)
        painter.begin(self.pixmapHolder)
        right_w = min(self.imageWidth, self.cellPixmap.width())
        right_h = min(self.imageHeight, self.cellPixmap.height())

        #because of asynchronous painting condition assignment
        # at the mouseMoveEvent func wouldn't keeps out
        self.x0 = self.x0 if self.x0 >= 0 else 0
        self.y0 = self.y0 if self.y0 >= 0 else 0

        screenPartWidth = min(self.imageWidth, self.cellPixmap.width())#*self.xScaled)
        screenPartHeight = min(self.imageHeight, self.cellPixmap.height())#*self.xScaled)

        painter.drawPixmap(0, 0, screenPartWidth, screenPartHeight, self.cellPixmap,
                           self.x0, self.y0, right_w, right_h)
        painter.end()

        #set pixmap, and resize Label
        if self.isImageLoaded:
            self.lbl.resize(self.imageWidth, self.imageHeight)
            self.lbl.setPixmap(self.pixmapHolder)
            height = self.pixmapHolder.height()
            width = self.pixmapHolder.width()
            #self.lbl.resize(min(width, self.imageWidth), min(height, self.imageHeight))

            '''
            #move label to the center of screen
            start_x = 0
            start_y = 0
            if width < self.imageWidth:
                start_x = (self.imageWidth - width) / 2
            if height < self.imageHeight:
                start_y = (self.imageHeight - height) / 2

            self.lbl.move(start_x, start_y)
            '''
        super().paintEvent(event)
示例#58
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     self.draw_board(painter)
     painter.end()
示例#59
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     self.draw_circles(qp)
     qp.end()
示例#60
0
文件: main.py 项目: rahpot/lisa
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     if self.ok != 0:
         self.drawCycles(qp)
     qp.end()