Esempio n. 1
0
 def image(cls, **kwargs):
     """
     Returns an image suitable for the palette.
     :rtype: QPixmap
     """
     # INITIALIZATION
     pixmap = QPixmap(kwargs['w'], kwargs['h'])
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     # INIT THE LINE
     p1 = QPointF(((kwargs['w'] - 54) / 2), kwargs['h'] / 2)
     p2 = QPointF(((kwargs['w'] - 54) / 2) + 54 - 2, kwargs['h'] / 2)
     line = QLineF(p1, p2)
     # CLACULATE HEAD COORDS
     angle = line.angle()
     p1 = QPointF(line.p2().x() + 2, line.p2().y())
     p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8)
     p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8)
     # INITIALIZE HEAD
     head = QPolygonF([p1, p2, p3])
     # DRAW EDGE LINE
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
     painter.drawLine(line)
     # DRAW EDGE HEAD
     painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
     painter.setBrush(QColor(0, 0, 0))
     painter.drawPolygon(head)
     return pixmap
Esempio n. 2
0
    def getMask(self, pixmap, x, y, w, h, shape, overlay,
                bg=QtCore.Qt.transparent, fg=QtCore.Qt.black, progressive=False):
        """Create a shape mask with the same size of pixmap.
        """
        mask = QPixmap(pixmap.width(), pixmap.height())
        mask.fill(bg)
        path = QtGui.QPainterPath()

        if progressive:
            progressive = QPixmap(pixmap.width(), pixmap.height())
            progressive.fill(QtCore.Qt.transparent)
            progressiveMask = QPixmap(self.MASK_PATH)
            progressiveMask = progressiveMask.scaled(w, h, QtCore.Qt.IgnoreAspectRatio)
            progressivePainter = QtGui.QPainter(progressive)
            progressivePainter.drawPixmap(x, y, progressiveMask)
            del progressivePainter
            fg = QtGui.QBrush(progressive)

        painter = QtGui.QPainter(mask)
        if shape == self.SHAPE_ELLIPSE:
            path.addEllipse(x, y, w, h)
            painter.fillPath(path, fg)
        elif shape == self.SHAPE_RECT:
            painter.fillRect(x, y, w, h, fg)

        painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceAtop)
        if overlay:
            painter.drawPixmap(0, 0, overlay)
        return mask
Esempio n. 3
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
Esempio n. 4
0
 def updateCircle(self, s):
     size = s * self.zoom
     pixmap = QPixmap(self.width(), self.height())
     pixmap.fill(Qt.transparent)
     #painter ellipse 1
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     pen = QPen(Qt.red)
     pen.setWidth(3)
     painter.setPen(pen)
     brush = QBrush(Qt.green)
     painter.setBrush(brush)
     painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter.end()
     #painter ellipse 2
     painter2 = QPainter()
     painter2.begin(pixmap)
     painter2.setRenderHint(QPainter.Antialiasing)
     pen2 = QPen(Qt.green)
     pen2.setStyle(Qt.DotLine)
     pen2.setWidth(3)
     painter2.setPen(pen2)
     painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter2.end()
     
     self.ellipseLabel.setPixmap(QPixmap(pixmap))
     self.lastSize = s
Esempio n. 5
0
def pixmap(cursor, num_lines=6, scale=0.8):
    """Return a QPixmap displaying the selected lines of the document.

    If the cursor has no selection, num_lines are drawn.

    By default the text is drawn 0.8 * the normal font size. You can change
    that by supplying the scale parameter.

    """
    block = cursor.document().findBlock(cursor.selectionStart())
    c2 = QTextCursor(block)
    if cursor.hasSelection():
        c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor)
        c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
    else:
        c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines)

    data = textformats.formatData('editor')
    doc = QTextDocument()
    font = QFont(data.font)
    font.setPointSizeF(font.pointSizeF() * scale)
    doc.setDefaultFont(font)
    doc.setPlainText(c2.selection().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlighter.highlight(doc, state=tokeniter.state(block))
    size = doc.size().toSize() + QSize(8, -4)
    pix = QPixmap(size)
    pix.fill(data.baseColors['background'])
    doc.drawContents(QPainter(pix))
    return pix
Esempio n. 6
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)
Esempio n. 7
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
Esempio n. 8
0
 def set_color(self, color):
     if color != self._color:
         self._color = color
         self.colorChanged.emit(self._color)
         pixmap = QPixmap(self.iconSize())
         pixmap.fill(color)
         self.setIcon(QIcon(pixmap))
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
Esempio n. 10
0
 def createListWidget(self):
     listWidget = QListWidget()
     w, h = self.ITEM_SIZE
     scroll_size = 16
     listWidget.setFixedWidth(w + scroll_size)
     listWidget.setAttribute(Qt.WA_MacShowFocusRect, False)
     for x in xrange(self._min_size, self._max_size):
         h = max(x + self.MARGIN * 2.0, h)
         pixmap = QPixmap(w, h)
         pixmap.fill(Qt.transparent)
         painter = QPainter(pixmap)
         center = h / 2.0
         painter.fillRect(QRectF(self.MARGIN, center - x / 2.0,
                                 w - self.MARGIN * 2.0, x), Qt.black)
         painter.end()
         label = QLabel()
         label.setPixmap(pixmap)
         item = QListWidgetItem(listWidget)
         item.setSizeHint(QSize(w, h))
         item.setData(Qt.UserRole, x)
         listWidget.addItem(item)
         listWidget.setItemWidget(item, label)
         if self._size == x:
             listWidget.setCurrentItem(item)
     return listWidget
 def __init__(self, color):
     QIcon.__init__(self)
     qcolor = QColor()
     qcolor.setNamedColor(color)
     pixmap = QPixmap(20, 20)
     pixmap.fill(qcolor)
     self.addPixmap(pixmap)
Esempio n. 12
0
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

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

    spinbox = DelayedSpinBox(750)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
Esempio n. 13
0
    def image(cls, **kwargs):
        """
        Returns an image suitable for the palette.
        :rtype: QPixmap
        """
        # INITIALIZATION
        pixmap = QPixmap(kwargs['w'], kwargs['h'])
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        # INITIALIZE EDGE LINE
        pp1 = QPointF(((kwargs['w'] - 52) / 2), kwargs['h'] / 2)
        pp2 = QPointF(((kwargs['w'] - 52) / 2) + 52 - 2, kwargs['h'] / 2)
        line = QLineF(pp1, pp2)
        # CALCULATE HEAD COORDINATES
        angle = radians(line.angle())
        p1 = QPointF(line.p2().x() + 2, line.p2().y())
        p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8)
        p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8)
        # INITIALIZE EDGE HEAD
        head = QPolygonF([p1, p2, p3])
        # DRAW THE POLYGON
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        painter.drawLine(line)
        # DRAW HEAD
        painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        painter.setBrush(QColor(0, 0, 0))
        painter.drawPolygon(head)
        # DRAW THE TEXT ON TOP OF THE EDGE
        space = 2 if Platform.identify() is Platform.Darwin else 0
        painter.setFont(Font('Arial', 9, Font.Light))
        painter.drawText(pp1.x() + space, (kwargs['h'] / 2) - 4, 'instanceOf')

        return pixmap
Esempio n. 14
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)
Esempio n. 15
0
 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)
Esempio n. 16
0
 def __cssLinkClass(self, icon, size=32):
     """
     Private method to generate a link class with an icon.
     
     @param icon icon to be included (QIcon)
     @param size size of the icon to be generated (integer)
     @return CSS class string (string)
     """
     cssString = \
         """a.{{0}} {{{{\n"""\
         """  padding-left: {0}px;\n"""\
         """  background: transparent url(data:image/png;base64,{1})"""\
         """ no-repeat center left;\n"""\
         """  font-weight: bold;\n"""\
         """}}}}\n"""
     pixmap = icon.pixmap(size, size)
     imageBuffer = QBuffer()
     imageBuffer.open(QIODevice.ReadWrite)
     if not pixmap.save(imageBuffer, "PNG"):
         # write a blank pixmap on error
         pixmap = QPixmap(size, size)
         pixmap.fill(Qt.transparent)
         imageBuffer.buffer().clear()
         pixmap.save(imageBuffer, "PNG")
     return cssString.format(
         size + 4,
         str(imageBuffer.buffer().toBase64(), encoding="ascii"))
Esempio n. 17
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])
Esempio n. 18
0
def colored_icon(name, color):
    pix = QPixmap(name)
    mask = pix.createMaskFromColor(QColor(Qt.black), Qt.MaskOutColor)
    if isinstance(color, str):
        color = QColor(color)
    pix.fill(color)
    pix.setMask(mask)
    return QIcon(pix)
Esempio n. 19
0
 def image(self):
     pixmap = QPixmap(250, 250)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setPen(QPen(Qt.black, 8))
     painter.translate(125, 125)
     painter.drawPolyline(self.myPolygon)
     return pixmap
Esempio n. 20
0
    def setFeatureVHeader(self, feature):
        self.feature = feature
        self.vHeaderName = feature.name
        self.setText(self.vHeaderName)

        pixmap = QPixmap(20, 20)
        pixmap.fill(Qt.transparent)
        self.setIcon(QIcon(pixmap))
    def get_context_menu(self, qpoint):
        """ override this method to customize the context menu """
        menu = QMenu(self)
        index = self.view.indexAt(qpoint)

        def add_action(menu, text, handler, icon=None):
            a = None
            if icon is None:
                a = QAction(text, self)
            else:
                a = QAction(icon, text, self)
            a.triggered.connect(handler)
            menu.addAction(a)

        add_action(menu, "Color selection", self._handle_color_selection)

        # duplication here with vstructui
        color_menu = menu.addMenu("Color selection...")

        # need to escape the closure capture on the color loop variable below
        # hint from: http://stackoverflow.com/a/6035865/87207
        def make_color_selection_handler(color):
            return lambda: self._handle_color_selection(color=color)

        for color in QT_COLORS:
            add_action(color_menu, "{:s}".format(color.name),
                       make_color_selection_handler(color.qcolor), make_color_icon(color.qcolor))

        start = self._hsm.start
        end = self._hsm.end
        cm = self.getColorModel()
        if (start == end and cm.is_index_colored(start)) or cm.is_region_colored(start, end):
            def make_remove_color_handler(r):
                return lambda: self._handle_remove_color_range(r)

            remove_color_menu = menu.addMenu("Remove color...")
            for cr in cm.get_region_colors(start, end):
                pixmap = QPixmap(10, 10)
                pixmap.fill(cr.color)
                icon = QIcon(pixmap)
                add_action(remove_color_menu,
                       "Remove color [{:s}, {:s}], len: {:s}".format(h(cr.begin), h(cr.end), h(cr.end - cr.begin)),
                       make_remove_color_handler(cr), make_color_icon(cr.color))

        menu.addSeparator()  # -----------------------------------------------------------------

        add_action(menu, "Copy selection (binary)", self._handle_copy_binary)
        copy_menu = menu.addMenu("Copy...")
        add_action(copy_menu, "Copy selection (binary)", self._handle_copy_binary)
        add_action(copy_menu, "Copy selection (text)", self._handle_copy_text)
        add_action(copy_menu, "Copy selection (hex)", self._handle_copy_hex)
        add_action(copy_menu, "Copy selection (hexdump)", self._handle_copy_hexdump)
        add_action(copy_menu, "Copy selection (base64)", self._handle_copy_base64)

        menu.addSeparator()  # -----------------------------------------------------------------

        add_action(menu, "Add origin", lambda: self._handle_add_origin(index))
        return menu
Esempio n. 22
0
 def setLabelColor(self):
     index = self.lstLabels.currentIndex()
     color = iconColor(self.mw.mdlLabels.item(index.row()).icon())
     self.colorDialog = QColorDialog(color, self)
     color = self.colorDialog.getColor(color)
     if color.isValid():
         px = QPixmap(32, 32)
         px.fill(color)
         self.mw.mdlLabels.item(index.row()).setIcon(QIcon(px))
         self.updateLabelColor(index)
Esempio n. 23
0
	def __init__(self, path, widget=None):
		super(ThumbnailItem, self).__init__(os.path.basename(path), widget)
		self.path = path
		self.setData(Qt.UserRole, self.path)

		emptypix = QPixmap(QSize(256, 256))
		emptypix.fill(self.listWidget().palette().window().color())
		self.setIcon(QIcon(emptypix))

		thumbnailmaker.maker.addTask(self.path)
Esempio n. 24
0
 def setRoundMask(self):
     bmp = QPixmap(self.size())
     bmp.fill(Qt.white)
     p = QPainter(bmp)
     p.setRenderHint(QPainter.Antialiasing)
     p.setBrush(QBrush(Qt.white))
     p.setCompositionMode(QPainter.CompositionMode_Clear)
     p.drawRoundedRect(0, 0, self.width(), self.height(), 3, 3)
     p.end()
     self.setMask(QRegion(QBitmap(bmp)))
Esempio n. 25
0
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio, self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height-self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Esempio n. 26
0
 def updateMarkColors(self):
     entries = settings.readMarkColors()
     self.markColorMenu.clear()
     pixmap = QPixmap(24, 24)
     none = self.markColorMenu.addAction("None", self.markColor)
     none.setData(None)
     for name, color in entries.items():
         action = self.markColorMenu.addAction(name, self.markColor)
         pixmap.fill(color)
         action.setIcon(QIcon(pixmap))
         action.setData(color)
Esempio n. 27
0
def applyEffectToPixmap(pixmap, effect):
    scene = QGraphicsScene()
    item = QGraphicsPixmapItem()
    item.setPixmap(pixmap)
    item.setGraphicsEffect(effect)
    scene.addItem(item)
    res = QPixmap(pixmap.size())
    res.fill(Qt.transparent)
    painter = QPainter(res)
    scene.render(painter)
    return res
Esempio n. 28
0
 def __init__(self):
     QTableWidgetItem.__init__(self)
     # init
     # ------------------------------------------------
     self.isExpanded = True
     self.isRootNode = False
     self.feature = None
     self.vHeaderName = None
     self.children = []
     pixmap = QPixmap(20, 20)
     pixmap.fill(Qt.transparent)
     self.setIcon(QIcon(pixmap))
Esempio n. 29
0
    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)
Esempio n. 30
0
 def getCursor(self):
     antialiasing_margin = 1
     size = self.pen.width()
     pixmap = QPixmap(size + antialiasing_margin * 2,
                      size + antialiasing_margin * 2)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     painter.drawEllipse(QRectF(QPointF(antialiasing_margin, antialiasing_margin),
                                QSizeF(size, size)))
     painter.end()
     return QCursor(pixmap)
Esempio n. 31
0
    def __init__(self, type):

        self._type = type
        self._store = {}
        self._reverse = {}
        self._default = None

        self._iconSize = novelwriter.CONFIG.pxInt(32)
        pixmap = QPixmap(self._iconSize, self._iconSize)
        pixmap.fill(QColor(100, 100, 100))
        self._defaultIcon = QIcon(pixmap)

        if self._type == self.STATUS:
            self._prefix = "s"
        elif self._type == self.IMPORT:
            self._prefix = "i"
        else:
            raise Exception("This is a bug!")

        return
Esempio n. 32
0
 def image(cls, **kwargs):
     """
     Returns an image suitable for the palette.
     :rtype: QPixmap
     """
     # INITIALIZATION
     pixmap = QPixmap(kwargs['w'], kwargs['h'])
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     polygon = cls.createPolygon(48, 30)
     # ITEM SHAPE
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
     painter.setBrush(QColor(252, 252, 252))
     painter.translate(kwargs['w'] / 2, kwargs['h'] / 2)
     painter.drawPolygon(polygon)
     # TEXT WITHIN THE SHAPE
     painter.setFont(Font('Arial', 11, Font.Light))
     painter.drawText(polygon.boundingRect(), Qt.AlignCenter, 'or')
     return pixmap
Esempio n. 33
0
class DrawingBoard(QWidget):
    def __init__(self):
        super(DrawingBoard, self).__init__()
        self.buffer = np.zeros((280, 280), dtype=np.uint8)
        self.pixmap = QPixmap(280, 280)
        self.pixmap.fill(QColor(222, 222, 222))
        self.painter = QPainter(self.pixmap)
        self.painter.setPen(QPen(QColor(0, 0, 0), 10))
        self.label = QLabel()
        self.label.setPixmap(self.pixmap)
        self.if_mouse_press = False
        layout = QHBoxLayout()
        layout.addWidget(self.label)
        self.setLayout(layout)
        self.setFixedSize(280, 280)

    def clear(self):
        self.pixmap.fill(QColor(222, 222, 222))
        self.buffer = np.zeros((280, 280), dtype=np.uint8)
        self.label.setPixmap(self.pixmap)

    def mouseMoveEvent(self, e):
        x = e.x()
        y = e.y()
        if self.if_mouse_press:
            if x >= 0 and x < 280 and y >= 0 and y < 280:
                self.painter.drawPoint(e.x(), e.y())
                self.buffer[e.y() - 8:e.y() + 8, e.x() - 8:e.x() + 8] = 1
                self.label.setPixmap(self.pixmap)

    def mousePressEvent(self, e):
        self.if_mouse_press = True

    def mouseReleaseEvent(self, e):
        self.if_mouse_press = False

    def mouseDoubleClickEvent(self, e):
        self.clear()

    def getData(self):
        return self.buffer[14:266:9, 14:266:9]
Esempio n. 34
0
 def topo_show(self, ListA: list, ListB: list, ListC: list):
     sip.delete(self.graphicsView.scene)
     # self.graphicsView.scene = QtWidgets.QGraphicsScene(0, 0, 800, 600)
     self.graphicsView.scene = QtWidgets.QGraphicsScene(0, 0, 1500, 1000)
     self.graphicsView.setScene(self.graphicsView.scene)
     self.graphicsView.setAlignment(QtCore.Qt.AlignHCenter
                                    | QtCore.Qt.AlignVCenter)
     # self.graphicsView.setSceneRect(0, 0, 1600, 1200)  # fix scene size 500 500
     self.graphicsView.setSceneRect(0, 0, 3000,
                                    1800)  # fix scene size 500 500
     self.graphicsView.setRenderHint(QPainter.Antialiasing)  ##设置视图的抗锯齿渲染模式。
     self.scene = QGraphicsScene()
     self.graphicsView.setScene(self.scene)
     root_nodeA = self.getRoot(ListA)
     root_nodeB = self.getRoot(ListB).getFirstChild()
     root_nodeC = self.getRoot(ListC).getFirstChild()
     color_A = QPen(Qt.green)
     ymax_A = self.single_topo(ListA, 0, 0, 0, root_nodeA, color_A)
     yby = ymax_A - 80
     color_B = QPen(Qt.darkCyan)
     ymax_B = self.single_topo(ListB, 10, yby, ymax_A, root_nodeB, color_B)
     ycy = ymax_B - 80
     color_C = QPen(Qt.cyan)
     self.single_topo(ListC, 20, ycy, ymax_B, root_nodeC, color_C)
     self.graphicsView.centerOn(0, 00)
     printer_pixmap = QPrinter(QPrinter.HighResolution)
     printer_pixmap.setPageSize(QPrinter.A4)
     printer_pixmap.setOutputFormat(QPrinter.PdfFormat)
     time_str = datetime.datetime.now().strftime('%Y%m%d-%H_%M_%S')
     pngname = '../backup/topo/' + time_str + '.pdf'
     printer_pixmap.setOutputFileName(pngname)
     outputimg = QPixmap(3840, 1160)
     outputimg.fill(Qt.white)
     self.graphicsView.viewport().render(outputimg)
     painter_pixmap = QPainter()
     painter_pixmap.begin(printer_pixmap)
     rect = painter_pixmap.viewport()
     multiple = 3 * rect.width() / outputimg.width()
     painter_pixmap.scale(multiple, multiple)
     painter_pixmap.drawPixmap(0, 0, outputimg)
     painter_pixmap.end()
    def initUI(self):
        self.ConstantLabel()          
        self.AnimationImage()
        self.ClassNameTextBox()
        self.ClassNameLabel()
        self.ButtonAddClass()
        self.ButtonRecord()
        self.ButtonTrain()
        self.Button_Message_Signal_Trained()
        
        # enabling the train button here. 
        #----------------------------------------------------------------------
        global live_record_stop
        
        if(live_record_stop == 1):
            # Enabling the "TRAINING" button.
            self.button_train.setEnabled(True)
            self.button_train.setToolTip('Data collected, click to start training.       ')
            self.button_train.setStyleSheet(""" QPushButton{color:#ffffff; background-color:#000000; font-weight:bold; border-radius:10px;} 
                                                        QPushButton:hover{color:#ffffff; background-color:#054A73; font-size:13px; font-weight:bold; border-radius:10px; border: 1.5px solid #ffffff;}
                                                        QPushButton:pressed{color:#000000; background-color:#35BEF4; border-radius:10px; border: 1.5px solid #000000;} """)
                    
            live_record_stop = 0
             
        else:
            # disabling the "TRAINING" button.
            self.button_train.setToolTip('Train button is currently disabled.   ')
            self.button_train.setEnabled(False)
            self.button_train.setStyleSheet(""" QPushButton{color:#000000; background-color:#6B6B6B; border-radius:10px;} """)        
         
        self.show()
         
        # showinging the blur image over the background.
        #----------------------------------------------------------------------
        self.label_blur_img = QLabel(self)
        color = QColor(0, 0, 0, 200)                                            # rgba color code here.
        pixmap = QPixmap(1000, 500)
        pixmap.fill(color)
#        pixmap = QPixmap('assets/pg_bg1.png')
        self.label_blur_img.setPixmap(pixmap)
        self.label_blur_img.resize(1000,500)
Esempio n. 36
0
    def _buildNovelList(self):

        self.theIndex.buildNovelList()
        self.numRows = len(self.theIndex.novelList)
        self.numCols = len(self.theIndex.tagIndex.keys())

        self.mainTable.clear()
        self.mainTable.setRowCount(self.numRows)
        self.mainTable.setColumnCount(self.numCols)

        for n in range(len(self.theIndex.novelList)):
            iDepth = self.theIndex.novelList[n][1]
            iTitle = self.theIndex.novelList[n][2]
            newItem = QTableWidgetItem("%s%s  " % ("  " * iDepth, iTitle))
            self.mainTable.setVerticalHeaderItem(n, newItem)

        theMap = self.theIndex.buildTagNovelMap(self.theIndex.tagIndex.keys())
        nCol = 0
        for theTag, theCols in theMap.items():
            newItem = QTableWidgetItem(" %s " % theTag)
            self.mainTable.setHorizontalHeaderItem(nCol, newItem)
            for n in range(len(theCols)):
                if theCols[n] == 1:
                    pxNew = QPixmap(10, 10)
                    pxNew.fill(QColor(0, 120, 0))
                    lblNew = QLabel()
                    lblNew.setPixmap(pxNew)
                    lblNew.setAlignment(Qt.AlignCenter)
                    lblNew.setAttribute(Qt.WA_TranslucentBackground)
                    self.mainTable.setCellWidget(n, nCol, lblNew)
                elif theCols[n] == 2:
                    pxNew = QPixmap(10, 10)
                    pxNew.fill(QColor(0, 0, 120))
                    lblNew = QLabel()
                    lblNew.setPixmap(pxNew)
                    lblNew.setAlignment(Qt.AlignCenter)
                    lblNew.setAttribute(Qt.WA_TranslucentBackground)
                    self.mainTable.setCellWidget(n, nCol, lblNew)
            nCol += 1

        return
Esempio n. 37
0
class Drawing(QWidget):
    def __init__(self, parent=None):
        super(Drawing, self).__init__(parent)
        self.setWindowTitle("绘图应用")
        self.pix = QPixmap()
        self.lastPoint = QPoint()
        self.endPoint = QPoint()
        self.initUi()

    def initUi(self):

        self.resize(600, 600)
        # 画布大小为400*400,背景为白色
        self.pix = QPixmap(600, 600)
        self.pix.fill(Qt.white)

    def paintEvent(self, event):
        pp = QPainter(self.pix)
        # 根据鼠标指针前后两个位置绘制直线
        pp.drawLine(self.lastPoint, self.endPoint)
        # 让前一个坐标值等于后一个坐标值,
        # 这样就能实现画出连续的线
        self.lastPoint = self.endPoint
        painter = QPainter(self)
        painter.drawPixmap(0, 0, self.pix)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):
        if event.buttons() and Qt.LeftButton:
            self.endPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        # 鼠标左键释放
        if event.button() == Qt.LeftButton:
            self.endPoint = event.pos()
            # 进行重新绘制
            self.update()
Esempio n. 38
0
    def updateItems(self):
        if not self._model:
            return

        if self.currentItem():
            self._lastID = self.currentItem().data(0, Qt.UserRole)

        self._updating = True
        self.clear()
        characters = self._model.getCharactersByImportance()

        for i, importanceLevel in enumerate(self.importanceMap):
            # Create category item
            cat = QTreeWidgetItem(self, [importanceLevel])
            cat.setBackground(0, QBrush(QColor(S.highlightLight)))
            cat.setForeground(0, QBrush(QColor(S.highlightedTextDark)))
            cat.setTextAlignment(0, Qt.AlignCenter)
            f = cat.font(0)
            f.setBold(True)
            cat.setFont(0, f)
            self.addTopLevelItem(cat)
            # cat.setChildIndicatorPolicy(cat.DontShowIndicator)

            for c in characters[i]:
                name = c.name()
                # Check if name passes filter
                if not self._filter.lower() in name.lower():
                    continue

                item = QTreeWidgetItem(cat, [name])
                item.setData(0, Qt.UserRole, c.ID())
                px = QPixmap(32, 32)
                color = QColor(c.color())
                px.fill(color)
                item.setIcon(0, QIcon(px))

                if c.ID() == self._lastID:
                    self.setCurrentItem(item)

        self.expandAll()
        self._updating = False
Esempio n. 39
0
def generateTheme(themeDatas, screenRect):
    # Window Background
    px = QPixmap(screenRect.size())
    px.fill(QColor(themeDatas["Background/Color"]))

    painter = QPainter(px)
    if themeDatas["Background/ImageFile"]:
        path = findBackground(themeDatas["Background/ImageFile"])
        _type = themeDatas["Background/Type"]
        if path and _type > 0:
            if _type == 1:  # Tiled
                painter.fillRect(screenRect, QBrush(QImage(path)))
            else:
                img = QImage(path)
                scaled = img.size()
                if _type == 3:  # Stretched
                    scaled.scale(screenRect.size(), Qt.IgnoreAspectRatio)
                elif _type == 4:  # Scaled
                    scaled.scale(screenRect.size(), Qt.KeepAspectRatio)
                elif _type == 5:  # Zoomed
                    scaled.scale(screenRect.size(),
                                 Qt.KeepAspectRatioByExpanding)

                painter.drawImage((screenRect.width() - scaled.width()) / 2,
                                  (screenRect.height() - scaled.height()) / 2,
                                  img.scaled(scaled))

    # Text Background
    textRect = themeTextRect(themeDatas, screenRect)

    painter.save()
    color = QColor(themeDatas["Foreground/Color"])
    color.setAlpha(themeDatas["Foreground/Opacity"] * 255 / 100)
    painter.setBrush(color)
    painter.setPen(Qt.NoPen)
    r = themeDatas["Foreground/Rounding"]
    painter.drawRoundedRect(textRect, r, r)
    painter.restore()

    painter.end()
    return px
Esempio n. 40
0
    def paint(self, clear_coupe=False):
        '''

        :param clear_coupe: This is used to override the ctrl button
        In this way we can also call paint from the main gui when Ctrl button is released
        :return:
        '''
        try:

            pixmap_bg = QPixmap(self.size())
            pixmap_bg.fill(QColor(255, 255, 255))
            painter = QPainter()
            painter.begin(pixmap_bg)
            if not self.slice is None:
                self.slice.paint(painter=painter,
                                 size=self.size(),
                                 show_traces=self.show_traces)

            # was the ctrl button pressed?
            modifiers = QApplication.keyboardModifiers()
            ctrl = bool(modifiers & Qt.ControlModifier)

            # if so, do we need to show a transparent coupe?
            if ctrl and not clear_coupe:
                if not self.app.reconstruction is None:
                    if not self.app.reconstruction.active_coupe is None:
                        coupe = self.app.reconstruction.coupes[
                            self.app.reconstruction.active_coupe]
                        pixmap = coupe.pixmap_trans
                        source = QRect(0, 0, pixmap.width(), pixmap.height())
                        # an arbitrary zoom factor of 2 for now
                        target = QRect(self.coupe_pos.x(), self.coupe_pos.y(),
                                       pixmap.width() * 2,
                                       pixmap.height() * 2)
                        painter.drawPixmap(target, pixmap, source)
            painter.end()
            self.setPixmap(pixmap_bg)
        except:
            self.logger.error(sys.exc_info()[0])
            self.logger.error(traceback.format_exc())
            pass
Esempio n. 41
0
    def __grabRect(self):
        """
        Private method to grab the selected rectangle (i.e. do the snapshot).
        """
        if self.__mode == SnapshotRegionGrabber.Ellipse:
            ell = QRegion(self.__selection, QRegion.Ellipse)
            if not ell.isEmpty():
                self.__grabbing = True

                xOffset = self.__pixmap.rect().x() - ell.boundingRect().x()
                yOffset = self.__pixmap.rect().y() - ell.boundingRect().y()
                translatedEll = ell.translated(xOffset, yOffset)

                pixmap2 = QPixmap(ell.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.drawEllipse(translatedEll.boundingRect())
                    pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
                else:
                    pt.setClipRegion(translatedEll)
                    pt.setCompositionMode(QPainter.CompositionMode_Source)

                pt.drawPixmap(pixmap2.rect(), self.__pixmap,
                              ell.boundingRect())
                pt.end()

                self.grabbed.emit(pixmap2)
        else:
            r = QRect(self.__selection)
            if not r.isNull() and r.isValid():
                self.__grabbing = True
                self.grabbed.emit(self.__pixmap.copy(r))
Esempio n. 42
0
    def _CircleCursor(self):
        """Draw a circle cursor of the same size as brush."""
        pixmap_size = 128
        pixmap = QPixmap(pixmap_size, pixmap_size)
        pixmap.fill(Qt.GlobalColor.transparent)

        # draw circle on pixmap among .begin() and .end() calls
        painter = QPainter()
        painter.begin(pixmap)
        if hasattr(self.canvas, 'zoom'):
            diameter = self.radius * self.canvas.zoom * 2
            if diameter > pixmap_size:
                print(f"Max displayed diameter {pixmap_size}")
        else:
            diameter = self.radius * 2
        left = (pixmap_size - diameter) // 2
        top = (pixmap_size - diameter) // 2
        # draw bbox in (left, top) with size (diameter, diameter)
        painter.drawEllipse(left, top, diameter, diameter)
        painter.end()
        return QCursor(pixmap)
Esempio n. 43
0
 def basefinished(self):
     if self.basereply.error() != QNetworkReply.NoError:
         return
     self.basepixmap = QPixmap()
     self.basepixmap.loadFromData(self.basereply.readAll())
     if self.basepixmap.size() != self.rect.size():
         self.basepixmap = self.basepixmap.scaled(self.rect.size(),
                                                  Qt.KeepAspectRatio,
                                                  Qt.SmoothTransformation)
     if self.satellite:
         p = QPixmap(self.basepixmap.size())
         p.fill(Qt.transparent)
         painter = QPainter()
         painter.begin(p)
         painter.setOpacity(0.6)
         painter.drawPixmap(0, 0, self.basepixmap)
         painter.end()
         self.basepixmap = p
         self.wwx.setPixmap(self.basepixmap)
     else:
         self.setPixmap(self.basepixmap)
 def drawPreviewWaveformPixmap(self):
   if self.data is None:
     return None
   pixmap = QPixmap(self.pixmap_width, self.pixmap_height)
   pixmap.fill(Qt.black)
   painter = QPainter()
   painter.begin(pixmap)
   painter.setBrush(Qt.SolidPattern)
   if self.data and len(self.data) >= self.pixmap_width*2:
     for x in range(0, self.pixmap_width):
       height = self.data[2*x]-2 # only seen from 2..23
       height = height if height > 0 else 0
       # self.data[2*x+1] only seen from 1..6
       color = blue_map[2] if self.data[2*x+1] > 3 else blue_map[6]
       painter.setPen(QColor(*color))
       painter.drawLine(x, 31, x, 31-height)
   # base line
   painter.setPen(Qt.white)
   painter.drawLine(0,33,399,33)
   painter.end()
   return pixmap
Esempio n. 45
0
    def pixmap(self, mode=QIcon.Normal, state=QIcon.Off):
        pixmap = self.icon().pixmap(self.iconSize(), mode, state)
        if pixmap.isNull():
            return pixmap

        size = max(pixmap.width(), pixmap.height())
        offset_x = (size - pixmap.width()) / 2
        offset_y = (size - pixmap.height()) / 2

        new_pixmap = QPixmap(size, size)
        new_pixmap.fill(Qt.transparent)
        path = QPainterPath()
        path.addRoundedRect(0, 0, size, size, 3.7, 3.7)
        painter = QPainter(new_pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
        painter.setClipPath(path)
        painter.drawPixmap(offset_x, offset_y, pixmap)
        painter.end()

        return new_pixmap
Esempio n. 46
0
    def _selectedItem(self):
        """Extract the info of a selected item and populate the settings
        boxes and button.
        """
        selItem = self._getSelectedItem()
        if selItem is None:
            return

        cols = selItem.data(self.COL_LABEL, self.COL_ROLE)
        name = selItem.text(self.COL_LABEL)

        pixmap = QPixmap(self.iPx, self.iPx)
        pixmap.fill(QColor(*cols))
        self.selColour = QColor(*cols)
        self.editName.setText(name)
        self.colButton.setIcon(QIcon(pixmap))
        self.editName.setEnabled(True)
        self.editName.selectAll()
        self.editName.setFocus()

        return
Esempio n. 47
0
 def setupGrid(self):
     self.boxes = []
     self.spacingX, self.spacingY = (self.paperW - self.cols * self.W) / (
         self.cols + 1), (self.paperH - self.rows * self.H) / (self.rows +
                                                               1)
     screenDPI = QApplication.desktop().logicalDpiX()
     self.scale = screenDPI / self.DPI
     w, h = self.W * self.scale, self.H * self.scale
     spacing_x, spacing_y = self.spacingX * self.scale, self.spacingY * self.scale
     for i in range(self.cols * self.rows):
         row, col = i // self.cols, i % self.cols
         box = QRect(spacing_x + col * (spacing_x + w),
                     spacing_y + row * (spacing_y + h), w - 1, h - 1)
         self.boxes.append(box)
     fg = QPixmap(self.paperW * self.scale, self.paperH * self.scale)
     fg.fill()
     painter = QPainter(fg)
     for box in self.boxes:
         painter.drawRect(box)
     painter.end()
     self.setPixmap(fg)
Esempio n. 48
0
 def image(cls, **kwargs):
     """
     Returns an image suitable for the palette.
     :rtype: QPixmap
     """
     # INITIALIZATION
     pixmap = QPixmap(kwargs['w'], kwargs['h'])
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     # TEXT
     painter.setFont(Font('Arial', 9, Font.Light))
     painter.translate(0, 0)
     painter.drawText(QRectF(0, 0, kwargs['w'], kwargs['h'] / 2),
                      Qt.AlignCenter, 'attribute')
     # ITEM SHAPE
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine))
     painter.setBrush(QColor(252, 252, 252))
     painter.translate(kwargs['w'] / 2, kwargs['h'] / 2 + 6)
     painter.drawEllipse(cls.createPolygon(18, 18))
     return pixmap
Esempio n. 49
0
    def _drawIcon(self, color=Qt.black):
        self.setForeground(QBrush(color))

        if self.isRootNode:
            pixmap = QPixmap(20, 20)
            pixmap.fill(Qt.transparent)
            painter = QPainter()
            painter.begin(pixmap)
            pen = QPen(color)
            pen.setWidth(1)
            painter.setPen(pen)
            painter.setBrush(color)
            painter.setRenderHint(QPainter.Antialiasing)
            if not self.isExpanded:
                arrowRightPolygon = [QPoint(6, 6), QPoint(6, 14), QPoint(14, 10)]
                painter.drawPolygon(QPolygon(arrowRightPolygon))
            else:
                arrowDownPolygon = [QPoint(6, 6), QPoint(15, 6), QPoint(10, 14)]
                painter.drawPolygon(QPolygon(arrowDownPolygon))
            painter.end()
            self.setIcon(QIcon(pixmap))
Esempio n. 50
0
def select_all_icon(color, base_size=QSize(48, 48)):
    """ Create the QGIS Select All icon with a dynamic color """
    output_pixmap = QPixmap(base_size)
    output_pixmap.fill(QColor("transparent"))
    painter = QPainter(output_pixmap)

    ratio = base_size.width() / 48.0

    stroke_color = color.darker()
    painter.setRenderHint(QPainter.Antialiasing)
    painter.setPen(QPen(stroke_color, 2 * ratio))
    painter.setBrush(color)
    painter.drawRect(4 * ratio, 3 * ratio, 40 * ratio, 11 * ratio)
    painter.drawRect(4 * ratio, 19 * ratio, 40 * ratio, 11 * ratio)
    painter.drawRect(4 * ratio, 35 * ratio, 40 * ratio, 11 * ratio)
    del painter

    icon = QIcon()
    icon.addPixmap(output_pixmap)

    return icon
    def __selectColourSlot(self):
        """
        Private slot to select a color.
        """
        button = self.sender()
        colorKey = button.property("colorKey")
        hasAlpha = button.property("hasAlpha")

        if hasAlpha:
            colour = QColorDialog.getColor(self.__coloursDict[colorKey][0],
                                           self, "",
                                           QColorDialog.ShowAlphaChannel)
        else:
            colour = QColorDialog.getColor(self.__coloursDict[colorKey][0],
                                           self)
        if colour.isValid():
            size = button.iconSize()
            pm = QPixmap(size.width(), size.height())
            pm.fill(colour)
            button.setIcon(QIcon(pm))
            self.__coloursDict[colorKey][0] = colour
Esempio n. 52
0
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Qt static label demo")
        width = 640
        height = 480
        # create the label that holds the image
        self.image_label = QLabel(self)
        # create a text label
        self.textLabel = QLabel('Demo')

        # create a vertical box layout and add the two labels
        vbox = QVBoxLayout()
        vbox.addWidget(self.image_label)
        vbox.addWidget(self.textLabel)
        # set the vbox layout as the widgets layout
        self.setLayout(vbox)
        # create a grey pixmap
        grey = QPixmap(width, height)
        grey.fill(QColor('darkGray'))
        # set the image image to the grey pixmap
        self.image_label.setPixmap(grey)
Esempio n. 53
0
 def __init__(self, filename):
     super().__init__()
     self.image_filename = filename
     self.setScene(QGraphicsScene(self))
     self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
     self.setDragMode(QGraphicsView.ScrollHandDrag)
     self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
     self.setFrameShape(QGraphicsView.NoFrame)
     self.setRenderHint(QPainter.SmoothPixmapTransform)
     # Menu
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self._show_menu)
     # Draw background
     pix = QPixmap(64, 64)
     pix.fill(QColor("#1e1e1e"))
     painter = QPainter(pix)
     color = QColor(20, 20, 20)
     painter.fillRect(0, 0, 32, 32, color)
     painter.fillRect(32, 32, 32, 32, color)
     painter.end()
     self.setBackgroundBrush(QBrush(pix))
Esempio n. 54
0
    def show_contour_info(self, event):
        x = event.pos().x()
        y = event.pos().y()
        qsize = self.image_frame.size()
        x *= self.img_handler.shape[0] / qsize.width()
        y *= self.img_handler.shape[1] / qsize.height()
        text_edit = self.textEdit2

        text_edit.setText(f"x:{x} y:{y}")
        for contour in self.img_handler.contours:
            left, bottom = contour.corner_bl
            right, top = contour.corner_tr

            if left <= x <= right and bottom <= y <= top:
                text_edit.append(f"Contour number: {contour.number}")
                text_edit.append(f"Contour left margin: {left}")
                text_edit.append(f"Contour right margin: {right}")
                text_edit.append(f"Contour bottom margin: {bottom}")
                text_edit.append(f"Contour top margin: {top}")
                text_edit.append(f"Object confidence: {contour.obj_conf}")
                text_edit.append(f"Class score: {contour.cls_score}")
                text_edit.append(f"Label: <b>{contour.label}</b>")
                if contour.id_track == -1:
                    text_edit.append(f"Tracking ID: No tracking")
                else:
                    text_edit.append(f"Tracking ID: {contour.id_track}")
                text_edit.append("Color: ")
                pix_map = QPixmap(20, 20)
                b, g, r = contour.color
                pix_map.fill(QColor(r, g, b))
                color_icon = pix_map.toImage()
                text_cursor = text_edit.textCursor()
                text_cursor.movePosition(QtGui.QTextCursor.NextCell,
                                         QtGui.QTextCursor.MoveAnchor)
                text_cursor.insertImage(color_icon)
                # This will hide the cursor
                blank_cursor = QtGui.QCursor(Qt.BlankCursor)
                text_edit.setCursor(blank_cursor)
                text_edit.moveCursor(QtGui.QTextCursor.End)
                return
Esempio n. 55
0
    def __init__(self, mainWindow, level, stage):
        super().__init__(mainWindow, objectName='gameGroup')

        gamePath = mainWindow.path + 'icons/'

        self.setGeometry(QRect(360, 0, 720, 520))
        self.setTitle('Game')

        self.gameFrame = QWidget(self, objectName='gameFrame')
        self.gameFrame.setStyleSheet('#gameFrame {border: 1px solid gray;}')
        self.gameFrame.setGeometry(QRect(5, 15, 710, 485))

        self.gameFrame.cheeseList, self.gameFrame.trapList, self.gameFrame.mouse = placeObjects(
            self.gameFrame, gamePath, level, stage)

        self.cheeseList = len(self.gameFrame.cheeseList)
        self.finish = False
        self.gameFrame.show()

        self.gameStatusLabel = QLabel(self, objectName='gameStatusLabel')
        self.gameStatusLabel.setEnabled(False)
        self.gameStatusLabel.setGeometry(QRect(10, 498, 701, 21))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.gameStatusLabel.setFont(font)
        self.gameStatusLabel.setText('Playing (' + str(self.cheeseList) +
                                     ' / ' +
                                     str(len(self.gameFrame.cheeseList)) +
                                     ' cheese remains)')

        self.gameFrame.label = QLabel(self.gameFrame)
        canvas = QPixmap(self.gameFrame.size().width(),
                         self.gameFrame.size().height())
        canvas.fill(QColor(0, 0, 0, 210))
        self.gameFrame.label.setPixmap(canvas)
        self.gameFrame.label.hide()

        self.show()
Esempio n. 56
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:
            root = QFileInfo(__file__).absolutePath()

            image = QImage(root + '/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)
Esempio n. 57
0
    def generateSceneImage(self, cs):
        sceneImg = QPixmap(CommonValues.DisplayWidth,
                           CommonValues.DisplayHeight)
        sceneImg.fill(Qt.transparent)
        imgFog = QImage(CommonValues.DisplayWidth, CommonValues.DisplayHeight,
                        QImage.Format_ARGB32)
        imgFog.fill(Qt.transparent)
        fogPainter = QPainter(imgFog)
        painter = QPainter(sceneImg)
        curSOS = cs.getSceneObjects()

        for so in curSOS["images"]:
            if not so.isHidden():
                img = so.getImage()
                d = so.getDimensions()
                if img is not None:
                    print("Drawing Image!")
                    print(d)
                    painter.drawPixmap(d[0] * CommonValues.PPI,
                                       d[1] * CommonValues.PPI, img)

        for so in curSOS["darkness"]:
            if not so.isHidden():
                d = so.getDimensions()
                fogPainter.setBrush(Qt.black)
                fogPainter.setPen(Qt.black)
                fogPainter.drawRect(d[0] * CommonValues.PPI,
                                    d[1] * CommonValues.PPI,
                                    d[2] * CommonValues.PPI,
                                    d[3] * CommonValues.PPI)

        for so in curSOS["light"]:
            if not so.isHidden():
                pass

        fogPainter.end()

        painter.drawImage(0, 0, imgFog)
        painter.end()
        return sceneImg
Esempio n. 58
0
 def makeCursor(self, whitePath, blackPath, x, y):
     pixmap = QPixmap(24, 24)
     pixmap.fill(Qt.transparent)
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, pixmap.height())
     painter.scale(1, -1)
     painter.fillPath(whitePath, Qt.white)
     painter.end()
     effect = QGraphicsDropShadowEffect()
     effect.setColor(QColor.fromRgbF(0, 0, 0, .3))
     effect.setBlurRadius(4)
     effect.setOffset(0, 1)
     pixmap = applyEffectToPixmap(pixmap, effect)
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, pixmap.height())
     painter.scale(1, -1)
     painter.fillPath(blackPath, Qt.black)
     painter.end()
     return QCursor(pixmap, x, y)
Esempio n. 59
0
 def initColour(self, colourKey, button, prefMethod, byName=False,
                hasAlpha=False):
     """
     Public method to initialize a colour selection button.
     
     @param colourKey key of the colour resource (string)
     @param button reference to a button to show the colour on (QPushButton)
     @param prefMethod preferences method to get the colour
     @keyparam byName flag indicating to retrieve/save by colour name
         (boolean)
     @keyparam hasAlpha flag indicating to allow alpha channel (boolean)
     """
     colour = QColor(prefMethod(colourKey))
     size = button.size()
     pm = QPixmap(size.width() / 2, size.height() / 2)
     pm.fill(colour)
     button.setIconSize(pm.size())
     button.setIcon(QIcon(pm))
     button.setProperty("colorKey", colourKey)
     button.setProperty("hasAlpha", hasAlpha)
     button.clicked.connect(self.__selectColourSlot)
     self.__coloursDict[colourKey] = [colour, byName]
Esempio n. 60
0
    def paintEvent(self, event):
        """
            Called when the widget is being painted
        """
        pixel_ratio = self.devicePixelRatioF()
        pixmap = QPixmap(self.width() * pixel_ratio,
                         self.height() * pixel_ratio)
        pixmap.setDevicePixelRatio(pixel_ratio)
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)

        # The server text region to be drawn
        server_region = QRegion(
            QRect(QPoint(0, 0), self._server_status_widget.sizeHint()))
        self._server_status_widget.render(painter, QPoint(0, 0), server_region)

        painter.end()

        painter = QPainter(self)
        painter.drawPixmap(event.rect(), pixmap, pixmap.rect())
        painter.end()