Exemplo n.º 1
0
    def saveAsPdf(self, fn, force=False):
        """
        Save bar image as a eps file.

        Args:
            fn: Filename
            force: if True, overwrites an existing file. If false, raises a
            RuntimeError if file already exists.
        """
        printer = QPrinter(QPrinter.HighResolution)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(fn)
        printer.setFullPage(True)
        printer.setPageSize(QPrinter.Custom)
        printer.setPaperSize(QSizeF(*self.size), QPrinter.Millimeter)
        printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter)

        painter = QPainter(printer)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawRect(QRect(0, 0, *self.size))

        targetrect = QRectF(0, 0, printer.width(), printer.height())
        sourcerect = QRectF(0, 0, *self.size)
        self.render(painter, targetrect, sourcerect)
        painter.end()
        return True
Exemplo n.º 2
0
    def saveAsBitmap(self, fn):
        """
        Save bar image as a jpg file. Overwrites a file already existing in
        filesystem.

        https://stackoverflow.com/questions/7451183/how-to-create-image-file\
        -from-qgraphicsscene-qgraphicsview#11642517

        Args:
            fn: Filename
        Returns:
            True on success
        """
        size = self.size
        pixelsx = max(1200, size[0])
        pixelsy = int(pixelsx*size[1]/size[0])
        imagesize = (pixelsx, pixelsy)
        image = QImage(pixelsx,
                       pixelsy,
                       QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawRect(QRect(0, 0, *imagesize))

        targetrect = QRectF(0, 0, *imagesize)
        sourcerect = QRectF(0, 0, *size)
        self.render(painter, targetrect, sourcerect)
        painter.end()

        return image.save(fn)
Exemplo n.º 3
0
 def boundingRect(self):
     if self.angle == 0:
         return QRectF(0, 0, self.w, self.h)
     else:
         sideLen = self.w + self.h
         rect = QRectF(0, 0, 2 * sideLen, 2 * sideLen)
         rect.moveTo(QPoint(-sideLen, -sideLen))
         return rect
Exemplo n.º 4
0
    def __init__(self, image, employee, text=u""):
        super(EmployeePictureItem, self).__init__(image)

        self.employee = employee

        # FIXME Clear ownership issues if any
        name = QGraphicsTextItem(self.employee.fullname + u" " + text, self)
        if image:
            name.setPos((image.width() - name.boundingRect().width()) / 2,
                        image.height())
            self.boundingBox = QRectF(0, 0, image.width(), 180)
        else:
            self.boundingBox = QRectF(0, 0,
                                      name.boundingRect().width(),
                                      name.boundingRect().height())
Exemplo n.º 5
0
    def paint(self, painter, option, widget):
        """
        TOWRITE

        :param `painter`: TOWRITE
        :type `painter`: `QPainter`_
        :param `option`: TOWRITE
        :type `option`: `QStyleOptionGraphicsItem`_
        :param `widget`: TOWRITE
        :type `widget`: `QWidget`_
        """
        objScene = self.scene()  # QGraphicsScene*
        if not objScene:
            return

        paintPen = self.pen()  # QPen
        painter.setPen(paintPen)
        self.updateRubber(painter)
        if option.state & QStyle.State_Selected:
            paintPen.setStyle(Qt.DashLine)
        if objScene.property(ENABLE_LWT):  # .toBool()
            paintPen = self.lineWeightPen()
        painter.setPen(paintPen)

        startAngle = (self.objectStartAngle() + self.rotation()) * 16  # qreal
        spanAngle = self.objectIncludedAngle() * 16                    # qreal

        if self.objectClockwise():
            spanAngle = -spanAngle

        rad = self.objectRadius()  # qreal
        paintRect = QRectF(-rad, -rad, rad * 2.0, rad * 2.0)
        painter.drawArc(paintRect, startAngle, spanAngle)
Exemplo n.º 6
0
    def getBarRect(self, n, g, yval):
        """
        Returns a bar QRectF.

        Args:
            n: Bar index (i.e. corresponding to a certain frequency band)
            g: Bar group (i.e. corresponding to a certain quantity)
            yval: Height of bar, 1 for full lenght, 0 for no length

        Returns:
            QRectF corresponding to the bar at the right place in the scene
        """
        assert yval >= 0 and yval <= 1, "Invalid yval"
        Lx = self.xsize-rightoffset-leftoffset
        Ly = self.ysize-topoffset - bottomoffset

        start = 10
        S = Lx - 2*start
        assert S > 0, "Size of bar field is too small."
        # Width of a single bar
        L = S/(self.N*self.G+dxbars*(self.N-1))
        xL = leftoffset+start
        x = g*L + n*(self.G*L+dxbars*L) + xL

        return QRectF(x,
                      self.ysize-bottomoffset-yval*Ly,
                      L,
                      yval*Ly)
Exemplo n.º 7
0
    def testDrawTextWithRectF(self):
        '''QPainter.drawText(QRectF, ... ,QRectF*) inject code'''
        rect = QRectF(100, 52.3, 100, 100)
        newRect = self.painter.drawText(rect, Qt.AlignCenter | Qt.TextWordWrap,
                                        self.text)

        self.assert_(isinstance(newRect, QRectF))
Exemplo n.º 8
0
    def paintEvent(self, ev):
        if self.isEnabled():
            color = self.color
            colorBorder = [0.4, 0.4, 0.4]
        else:
            color = [0.8, 0.8, 0.8]
            colorBorder = [0.7, 0.7, 0.7]

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.HighQualityAntialiasing)

        if self.isChecked():
            pen = QPen(QColor.fromRgbF(0.2, 0.2, 0.2))
            pen.setWidth(2.0)
        else:
            pen = QPen(
                QColor.fromRgbF(colorBorder[0], colorBorder[1],
                                colorBorder[2]))
            pen.setWidth(1.0)

        size = self.size()
        sizeCircle = 12.0
        x = size.width() / 2.0 - (sizeCircle / 2.0)
        y = size.height() / 2.0 - (sizeCircle / 2.0)
        rect = QRectF(x, y, sizeCircle, sizeCircle)
        painter.setPen(pen)
        painter.setBrush(QColor.fromRgbF(color[0], color[1], color[2]))
        painter.drawEllipse(rect)
Exemplo n.º 9
0
 def testQRectWithFull(self):
     '''QFontMetricsF.boundingRect(QRectF, ...) - all arguments'''
     arg = QRectF(0, 0, 100, 200)
     rect = self.metrics.boundingRect(arg, Qt.TextExpandTabs | Qt.AlignLeft,
                                      'PySide by INdT', 20,
                                      [1, 2, 3, 4, 5])
     self.assertTrue(isinstance(rect, QRectF))
Exemplo n.º 10
0
 def setc1(self, path):
     self.c1scene.clear()
     self.c1 = Carrier(img=imread(path))
     size = len(self.c1.pixelData)
     if self.c1.img.ndim == 3:
         size *= 3
     size /= 8
     self.c1size = int(size)
     self.txtCarrierSize.setText(str(self.c1size))
     if self.c1.payloadExists():
         self.lblPayloadFound.setText(">>>>Payload Found<<<<")
         self.chkOverride.setEnabled(True)
     else:
         self.lblPayloadFound.setText("")
         self.chkOverride.setChecked(False)
         self.chkOverride.setEnabled(False)
     w, h = int(self.viewCarrier1.geometry().width()), int(
         self.viewCarrier1.geometry().height())
     pixMap = QPixmap(path)
     self.c1scene.addPixmap(
         pixMap.scaled(QSize(w, h), Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
     self.viewCarrier1.setScene(self.c1scene)
     self.viewCarrier1.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
     self.checkEmbed()
Exemplo n.º 11
0
    def testGetCoordsAndRect(self):
        rect1 = QRect(1, 2, 3, 4)
        self.assertEqual(rect1.getRect(), (1, 2, 3, 4))
        self.assertEqual(rect1.getCoords(), (1, 2, 3, 5))

        rect1 = QRectF(1, 2, 3, 4)
        self.assertEqual(rect1.getRect(), (1, 2, 3, 4))
        self.assertEqual(rect1.getCoords(), (1, 2, 4, 6))
Exemplo n.º 12
0
    def itemAt(self, position):
        items = self.scene.items(QRectF( position - QPointF(2,2) , QSizeF(4,4) ))

        for item in items:
            if item.type() > QGraphicsItem.UserType:
                return item

        return None
Exemplo n.º 13
0
    def request_relayout(self):

        if self.graph is None:
            return

        # remove all edges
        for p in self._edge_paths:
            self.scene.removeItem(p)

        # remove all nodes
        self.blocks.clear()
        self.remove_all_children()
        self._edge_paths = []

        node_sizes = {}
        for node in self.graph.nodes():
            self.blocks.add(node)
            node_sizes[node] = (node.width, node.height)
        gl = GraphLayouter(self.graph,
                           node_sizes,
                           compare_nodes_func=lambda n0, n1: 0)

        self._edges = gl.edges

        min_x, max_x, min_y, max_y = 0, 0, 0, 0

        for node, coords in gl.node_coordinates.iteritems():
            node.x, node.y = coords

            min_x = min(min_x, node.x)
            max_x = max(max_x, node.x + node.width)
            min_y = min(min_y, node.y)
            max_y = max(max_y, node.y + node.height)

        min_x -= self.LEFT_PADDING
        max_x += self.LEFT_PADDING
        min_y -= self.TOP_PADDING
        max_y += self.TOP_PADDING
        width = (max_x - min_x) + 2 * self.LEFT_PADDING
        height = (max_y - min_y) + 2 * self.TOP_PADDING

        self._update_size()

        # scrollbars
        self.horizontalScrollBar().setRange(min_x, max_x)
        self.verticalScrollBar().setRange(min_y, max_y)

        self.setSceneRect(QRectF(min_x, min_y, width, height))

        self.viewport().update()

        self._update_size()

        if self.selected is not None:
            self.show_selected()
        else:
            self.show_any()
Exemplo n.º 14
0
    def getRect(self):
        start = self.startPos
        end = self.endPos

        x = min(start.x(), end.x())
        y = min(start.y(), end.y())
        w = abs(start.x() - end.x())
        h = abs(start.y() - end.y())

        return QRectF(x, y, w, h)
Exemplo n.º 15
0
    def updateArcRect(self, radius):
        """
        TOWRITE

        :param `radius`: TOWRITE
        :type `radius`: qreal
        """
        arcRect = QRectF()
        arcRect.setWidth(radius * 2.0)
        arcRect.setHeight(radius * 2.0)
        arcRect.moveCenter(QPointF(0, 0))
        self.setRect(arcRect)
Exemplo n.º 16
0
 def paintEvent(self, event):
     super().paintEvent(event)
     letterPen = QPen(Qt.darkGreen if self.isEnabled() else Qt.lightGray)
     wordPen = QPen(Qt.darkCyan if self.isEnabled() else Qt.lightGray)
     painter = QPainter(self)
     painter.setRenderHints(QPainter.TextAntialiasing)
     painter.setPen(letterPen)
     heightOne = self.fontMetrics().height()
     widthOne = self.fontMetrics().width("W")
     if self.orientation == Qt.Vertical:
         y = HANDLE_OFFSET
         for c in self.letters:
             rect = QRectF(X_OFFSET, y, widthOne, heightOne)
             painter.drawText(rect, Qt.AlignCenter, c)
             y += heightOne
         if self.word is not None:
             painter.setFont(self.smallFont)
             painter.setPen(wordPen)
             rect = self.rect().adjusted(0, HANDLE_OFFSET, -widthOne / 3, 0)
             painter.drawText(rect,
                              Qt.AlignTop | Qt.AlignRight | Qt.TextWordWrap,
                              "\n".join(self.word.lower()))
             painter.setPen(letterPen)
             painter.setFont(self.mainFont)
     else:
         widthOne *= H_GAP_PC
         x = HANDLE_OFFSET
         for c in self.letters:
             rect = QRectF(x, 0, widthOne, heightOne * V_GAP_PC)
             painter.drawText(rect, Qt.AlignCenter, c)
             x += widthOne
         if self.word is not None:
             painter.setFont(self.smallFont)
             painter.setPen(wordPen)
             rect = self.rect().adjusted(HANDLE_OFFSET, 0, 0, 0)
             painter.drawText(rect, Qt.AlignBottom | Qt.AlignLeft,
                              self.word.lower())
             painter.setPen(letterPen)
             painter.setFont(self.mainFont)
Exemplo n.º 17
0
    def setObjectDiameter(self, diameter):
        """
        TOWRITE

        :param `diameter`: TOWRITE
        :type `diameter`: qreal
        """
        circRect = QRectF()
        circRect.setWidth(diameter)
        circRect.setHeight(diameter)
        circRect.moveCenter(QPointF(0, 0))
        self.setRect(circRect)
        self.updatePath()
Exemplo n.º 18
0
 def onExtract(self):
     payload = self.c2.extractPayload()
     image = ImageQt.ImageQt(Image.fromarray(payload.img[:-1]))
     pixMap = QPixmap.fromImage(image)
     w, h = int(self.viewPayload2.geometry().width()), int(
         self.viewPayload2.geometry().height())
     self.p2scene.clear()
     self.p2scene.addPixmap(
         pixMap.scaled(QSize(w, h), Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
     self.viewPayload2.setScene(self.p2scene)
     self.viewPayload2.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
     self.btnExtract.setEnabled(False)
Exemplo n.º 19
0
    def request_relayout(self, ensure_visible=True):

        node_coords, edges = self._layout_graph()

        self._edges = edges

        categorize_edges(self.disasm, edges)

        if not node_coords:
            print "Failed to get node_coords"
            return

        min_x, max_x, min_y, max_y = 0, 0, 0, 0

        # layout nodes
        for block in self.blocks:
            x, y = node_coords[block.addr]
            block.x, block.y = x, y

            min_x = min(min_x, block.x)
            max_x = max(max_x, block.x + block.width)
            min_y = min(min_y, block.y)
            max_y = max(max_y, block.y + block.height)

            # self._set_pos(widget_proxy, self.mapToScene(x, y))

        min_x -= self.LEFT_PADDING
        max_x += self.LEFT_PADDING
        min_y -= self.TOP_PADDING
        max_y += self.TOP_PADDING
        width = (max_x - min_x) + 2 * self.LEFT_PADDING
        height = (max_y - min_y) + 2 * self.TOP_PADDING

        self._update_size()

        # scrollbars
        self.horizontalScrollBar().setRange(min_x, max_x)
        self.verticalScrollBar().setRange(min_y, max_y)

        self.setSceneRect(QRectF(min_x, min_y, width, height))

        self.viewport().update()

        self._update_size()

        if ensure_visible:
            if self.selected_insns:
                self.show_selected()
            else:
                self.show_instruction(self._function_graph.function.addr)
Exemplo n.º 20
0
	def paintEvent(self, ev):
		size = self.size()
		height = size.height()-5
		width = size.width()-5

		offset = 0.5
		rect = QRectF(2.0+offset, 2.0+offset, width, height)
		painter = QPainter(self)

		painter.setPen(self._pen)
		painter.setBrush(QColor(self._color[0], self._color[1], self._color[2]))
		painter.setRenderHint(QPainter.Antialiasing)
		painter.setRenderHint(QPainter.HighQualityAntialiasing)
		painter.drawRoundedRect(rect, 4, 4)
Exemplo n.º 21
0
    def updateBoundingRect(self):
        margin = self.keySize * 0.5

        boundingRect = QRectF(0, 0, 0, 0)

        for key in self.keyList:
            rect = key.shape().boundingRect()
            rect.translate(key.pos())
            boundingRect = boundingRect.united(rect)

        boundingRect.setX(boundingRect.x() - margin)
        boundingRect.setY(boundingRect.y() - margin)
        boundingRect.setWidth(boundingRect.width() + margin)
        boundingRect.setHeight(boundingRect.height() + margin)
        self.keyBoundRect = boundingRect
Exemplo n.º 22
0
 def drawImage(self, x, y, rx, ry, hImg):
     h = self.v.height()
     x0, y0 = self.t.transform(x, y)
     rx = self.t.sx * rx
     ry = self.t.sy * ry
     #self.qPainter.drawRect(x0,h-y0,rx,-ry)
     r = QRectF(x0, h - y0 - ry, rx, ry)
     qImg = hImg.convertMatToQImage(rx, ry)
     #r=QRectF(x0,h-y0-ry,qImg.width()/2,qImg.height()/2)
     #qImg=QImage('../images/im2.png')
     #mat=hImg.convertQImageToMat(qImg)
     #cv2.imshow('nada',hImg.getData())
     #print mat.shape
     #qImg=OpenCVQImage(mat)
     #qImgs=qImg.scaled(int(rx),int(ry))
     #qImg=QImage('../images/CAM00293.jpg')
     #cvi=cv2.imread('../images/CAM00293.jpg')
     self.qPainter.drawImage(r, qImg)
Exemplo n.º 23
0
    def setp1(self, path):
        self.chkApplyCompression.setEnabled(True)
        self.chkApplyCompression.setChecked(False)
        self.txtCompression.setEnabled(False)
        self.slideCompression.setEnabled(False)
        self.slideCompression.setValue(0)
        self.lblLevel.setEnabled(False)
        self.compressionLevel = -1

        self.p1scene.clear()
        self.p1 = Payload(img=imread(path))
        self.p1sizeCalc()
        w, h = int(self.viewPayload1.geometry().width()), int(
            self.viewPayload1.geometry().height())
        pixMap = QPixmap(path)
        self.p1scene.addPixmap(
            pixMap.scaled(QSize(w, h), Qt.KeepAspectRatio,
                          Qt.SmoothTransformation))
        self.viewPayload1.setScene(self.p1scene)
        self.viewPayload1.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
Exemplo n.º 24
0
    def selectObjects(self):
        for obj in self.mapWidget.mapObjects():
            obj.setSelected(False)

        if len(self.markerObjects) < 2:
            return

        bottomRight = self.markerObjects.pop()
        topLeft = self.markerObjects.pop()

        self.mapWidget.removeMapObject(topLeft)
        self.mapWidget.removeMapObject(bottomRight)

        selectedObjects = self.mapWidget.mapObjectsInScreenRect(
                    QRectF(self.mapWidget.coordinateToScreenPosition(topLeft.coordinate()),
                           self.mapWidget.coordinateToScreenPosition(bottomRight.coordinate()))
                )

        for obj in selectedObjects:
            obj.setSelected(True)
Exemplo n.º 25
0
 def update_handles_pos(self):
     """
     Update current resize handles according to the shape size and position.
     """
     s = self.handleSize
     b = self.boundingRect()
     self.handles[self.handleTopLeft] = QRectF(b.left(), b.top(), s, s)
     self.handles[self.handleTopMiddle] = QRectF(b.center().x() - s / 2,
                                                 b.top(), s, s)
     self.handles[self.handleTopRight] = QRectF(b.right() - s, b.top(), s,
                                                s)
     self.handles[self.handleMiddleLeft] = QRectF(b.left(),
                                                  b.center().y() - s / 2, s,
                                                  s)
     self.handles[self.handleMiddleRight] = QRectF(b.right() - s,
                                                   b.center().y() - s / 2,
                                                   s, s)
     self.handles[self.handleBottomLeft] = QRectF(b.left(),
                                                  b.bottom() - s, s, s)
     self.handles[self.handleBottomMiddle] = QRectF(b.center().x() - s / 2,
                                                    b.bottom() - s, s, s)
     self.handles[self.handleBottomRight] = QRectF(b.right() - s,
                                                   b.bottom() - s, s, s)
Exemplo n.º 26
0
 def setc2(self, path):
     self.c2fpath = path
     self.c2scene.clear()
     self.c2 = Carrier(img=imread(path))
     w, h = int(self.viewCarrier2.geometry().width()), int(
         self.viewCarrier2.geometry().height())
     pixMap = QPixmap(path)
     self.c2scene.addPixmap(
         pixMap.scaled(QSize(w, h), Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
     self.viewCarrier2.setScene(self.c2scene)
     self.viewCarrier2.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
     if self.c2.payloadExists():
         self.lblCarrierEmpty.setText("")
         self.btnExtract.setEnabled(True)
         self.btnClean.setEnabled(True)
     else:
         self.lblCarrierEmpty.setText(">>>>Carrier Empty<<<<")
         self.btnExtract.setEnabled(False)
         self.btnClean.setEnabled(False)
     self.p2scene.clear()
     self.viewPayload2.setScene(self.p2scene)
Exemplo n.º 27
0
    def dataChanged(self, topLeft, bottomRight):
        """QAbstractItemView virtual
        """
        debug_print('GraphicsItemView.dataChanged', topLeft.row(),
                    bottomRight.row())

        for row in xrange(topLeft.row(), 1 + bottomRight.row()):
            # new is a QRect - integer coordinates
            new = self.model().index(row, 0).data(RectRole)

            # Cumbersome conversion to ints
            item = self._rows[row]
            current = item.sceneBoundingRect()
            current = QRect(current.left(), current.top(), current.width(),
                            current.height())
            if current != new:
                msg = 'Update rect for [{0}] from [{1}] to [{2}]'
                debug_print(msg.format(row, current, new))
                item.prepareGeometryChange()

                # setrect() expects floating point rect
                item.setRect(QRectF(new))
Exemplo n.º 28
0
    def __init__(self, theScene, parent=None):
        """
        Default class constructor.

        :param `theScene`: TOWRITE
        :type `theScene`: `QGraphicsScene`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(EmbDetailsDialog, self).__init__(parent)

        self.setMinimumSize(750, 550)

        self.getInfo()
        self.mainWidget = self.createMainWidget()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)

        vboxLayoutMain = QVBoxLayout(self)
        vboxLayoutMain.addWidget(self.mainWidget)
        vboxLayoutMain.addWidget(self.buttonBox)
        self.setLayout(vboxLayoutMain)

        self.setWindowTitle(self.tr("Embroidery Design Details"))

        QApplication.setOverrideCursor(Qt.ArrowCursor)

        self.stitchesTotal = int()
        self.stitchesReal = int()
        self.stitchesJump = int()
        self.stitchesTrim = int()
        self.colorTotal = int
        self.colorChanges = int()

        self.boundingRect = QRectF()
Exemplo n.º 29
0
    def mousePressEvent(self, event):
        """QGraphicsView virtual
        """
        debug_print('BoxesView.mousePressEvent')

        p = self.mapToScene(self.mapFromGlobal(QtGui.QCursor.pos()))
        if Qt.RightButton == event.button() and not self.scene().is_empty:
            # TODO Rubber-band drag uses dashed black line - difficult to see on
            # images with a dark background
            if self._pending_box:
                debug_print('Expected self._pending_box to be empty')
            else:
                debug_print('Starting a new box')
                # The user is creating a new box
                # Create a temporary box (self._pending_box) that is used only
                # to provide feedback as the user drags the mouse
                # TODO LH Escape key cancels new box
                tl = self.mapToScene(event.pos())
                r = self.scene().addRect(QRectF(tl, QSizeF(0, 0)), Qt.DotLine)
                r.setZValue(3)  # Above all other items
                r.update()
                self._pending_box = r
        else:
            super(BoxesView, self).mousePressEvent(event)
Exemplo n.º 30
0
 def showEvent(self, event):
     self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size()))
     self.mapWidget.resize(self.view.size())