Ejemplo n.º 1
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)
Ejemplo n.º 2
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
Ejemplo 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
Ejemplo 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())
Ejemplo n.º 5
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))
Ejemplo n.º 6
0
    def setPixmap(self, pixmap):
        '''Set the array to be viewed.
        Args:
        array (numpy array): the array to be viewed

        This will remove the previous array but maintain the previous scaling
        as well as the panned position.
        '''
        self.pixmap = pixmap
        self.pixmapItem.setPixmap(self.pixmap)

        # Constrain scene to be the boundary of the pixmap
        pad = 5
        r = self.pixmapItem.boundingRect()
        r = QRectF(r.left()-pad,r.top()-pad,r.width()+2*pad,r.height()+2*pad)
        self.setSceneRect(r)
Ejemplo 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))
Ejemplo 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)
Ejemplo n.º 9
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()
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo 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
Ejemplo n.º 13
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))
Ejemplo n.º 14
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()
Ejemplo n.º 15
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)
Ejemplo n.º 16
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)
Ejemplo 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()
Ejemplo 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)
Ejemplo n.º 19
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)
    def paintEvent(self, event):
        #mtx = self.mtx
        mtx = QTransform()
        mtx.rotate(self.mrotation)
        mtx.scale(self.mscale.x(), self.mscale.y())
        mtx.translate(self.mtranslate.x(), self.mtranslate.y())
        eyepos = QPointF(self.epx, self.dof)
        ppoi = QPointF(self.ppx, self.ppy)
        point = QRectF(0.0,0.0,0.05,0.05);

        tpoi = mtx.map(ppoi)
        teyepos = mtx.map(eyepos)
        evec = QVector2D(tpoi - teyepos).normalized()

        pts = find_points(float2(tpoi.x(),tpoi.y()), float2(evec.x(), evec.y()))
        print pts
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.scale(self.width()/5.0,self.height()/5.0)
        qp.translate(2.5,2.5)
        #draw voxel bounds
        qp.drawRect(QRectF(0.0,0.0,1.0,1.0))
        #qp.transform(mtx)
        #draw eyepos
        point.moveTo(mtx.map(eyepos))
        qp.fillRect(point, QColor("black"))
        point.moveTo(mtx.map(ppoi))
        qp.fillRect(point, QColor("grey"))
        qp.setPen(QColor("cyan"))
        qp.drawLine(mtx.map(QLineF(-0.5,0.0,1.5,0.0)))
        qp.setPen(QColor("blue"))
        qp.drawLine(mtx.map(QLineF(-0.0,0.0,1.0,0.0)))
        qp.setPen(QColor("lime"))
        qp.drawLine(QLineF(eyepos,ppoi))
        qp.setPen(QColor("green"))
        qp.drawLine(QLineF(teyepos,tpoi))
        qp.setPen(QColor("orange"))
        qp.drawLine(QLineF(pts['x'],pts['y'],pts['z'], pts['w']))
        point.moveTo(QPointF(pts['x'],pts['y']))
        qp.fillRect(point, QColor("red"))
        point.moveTo(QPointF(pts['z'],pts['w']))
        qp.fillRect(point, QColor("pink"))
        qp.end()
Ejemplo n.º 21
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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
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()
Ejemplo n.º 24
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()
Ejemplo n.º 25
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)
Ejemplo n.º 26
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)
Ejemplo n.º 27
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)
Ejemplo n.º 28
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)
Ejemplo n.º 29
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)
Ejemplo n.º 30
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))
Ejemplo n.º 31
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()
Ejemplo n.º 32
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)
Ejemplo n.º 33
0
 def showEvent(self, event):
     self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size()))
     self.mapWidget.resize(self.view.size())
Ejemplo n.º 34
0
class Axis():

	# Rect holds the bounding box for the view of the graph
	rect = None

	# A list of the objects that axes has in the scene
	sceneObjects = None

	# Determines whether the axis text is drawn
	axisTextEnabled = True

	# Tick marks
	numXAxisMajor = 5
	numYAxisMajor = 5

	# Creates and draws the axes objects for the current view
	# Initially zoomed on a 2x2 view centered at 0,0
	def __init__(self,graphicsView):
		self.scene = graphicsView.scene()
		self.gView = graphicsView
		self.rect = Rect(-1,1,2,2)
		self.update()

	# Updates the transform so the axes draw the given rect
	def setAxisView(self, rect):
		self.rect = rect
		self.update()

	# Should be called any time the view is scaled or updated
	def update(self):

		# Update the scaling based on the viewport size
		self.xScale = self.gView.size().width()/self.rect.width()
		self.yScale = self.gView.size().height()/self.rect.height()

		if self.sceneObjects is not None:
			for o in self.sceneObjects:
				self.scene.removeItem(o)

		self.sceneObjects = []
		
		r = self.rect

		# Add the lines
		# Is x = 0 in the current view?
		if r.left() < 0 and r.right() > 0:
			self.sceneObjects.append(self.scene.addLine(0,r.bottom(),0,r.top()))
			yaLoc = 0
		# Otherwise, add the line in the middle of the view
		else:
			self.sceneObjects.append(self.scene.addLine(r.center().x(),r.bottom(),r.center().x(),r.top()))
			yaLoc = r.center().x()

		# Is y = 0 in the current view? Note that top and bottom are reversed, due to -1 transform
		if r.top() < 0 and r.bottom() > 0:
			self.sceneObjects.append(self.scene.addLine(r.left(),0,r.right(),0))
			xaLoc = 0
		# Otherwise, add the line in the middle of the view
		else:
			self.sceneObjects.append(self.scene.addLine(r.left(),r.center().y(),r.right(),r.center().y()))
			xaLoc = r.center().y()

		# Draw the tick marks
		xaMajSpacing = 0
		mult = 1.0
		while xaMajSpacing == 0:
			xaMajSpacing = math.floor(mult*r.width()*1.0/(self.numXAxisMajor+1))/mult
			mult *= 10.0

		yaMajSpacing = 0
		mult = 1.0
		while yaMajSpacing == 0:
			yaMajSpacing = math.floor(mult*r.height()*1.0/(self.numYAxisMajor+1))/mult
			mult *= 10.0

		x = -xaMajSpacing + yaLoc
		while x > r.left():
			self.sceneObjects.append(self.scene.addLine(x, xaLoc - 5/self.yScale, x, xaLoc + 5/self.yScale))
			if self.axisTextEnabled:
				self.addText(str(x), x, xaLoc - 6/self.yScale, alignTop = True)
			x -= xaMajSpacing

		x = xaMajSpacing + yaLoc
		while x < r.right():
			self.sceneObjects.append(self.scene.addLine(x, xaLoc - 5/self.yScale, x, xaLoc + 5/self.yScale))
			if self.axisTextEnabled:
				self.addText(str(x), x, xaLoc - 6/self.yScale, alignTop = True)
			x += xaMajSpacing				

		y = -yaMajSpacing + xaLoc
		while y > r.top():
			self.sceneObjects.append(self.scene.addLine(-5/self.xScale + yaLoc, y, 5/self.xScale + yaLoc, y))
			if self.axisTextEnabled:
				self.addText(str(y), yaLoc + 7.5/self.xScale, y, alignLeft = True)
			y -= yaMajSpacing

		y = yaMajSpacing + xaLoc
		while y < r.bottom():
			self.sceneObjects.append(self.scene.addLine(-5/self.xScale + yaLoc, y, 5/self.xScale + yaLoc, y))
			if self.axisTextEnabled:
				self.addText(str(y), yaLoc + 7.5/self.xScale, y, alignLeft = True)
			y += yaMajSpacing				

	# Adds text centered at x and y
	def addText(self, text, x, y, alignLeft = False, alignTop = False):
		t = self.scene.addText(text)

		# Undo transform
		t.setTransform(t.transform().scale(1/self.xScale,-1/self.yScale))

		tR = t.sceneBoundingRect()
		if not alignLeft:
			xLoc = x - tR.width()/2
		else:
			xLoc = x

		if not alignTop:
			yLoc = y + tR.height()/2
		else:
			yLoc = y


		r = self.rect
		if xLoc < r.left():
			xLoc = r.left()
		elif xLoc + tR.width() > r.right():
			xLoc = r.right() - tR.width()

		if yLoc < r.top():
			yLoc = r.top()
		elif yLoc - tR.height() > r.bottom():
			yLoc = r.bottom() - tR.height()

		t.setPos(xLoc, yLoc)

		self.sceneObjects.append(t)

	# Get the actual pixel coordinates of the given position
	def getPixelCoords(self, pos):
		p = [(pos[0] - self.rect.left()) * self.xScale, (pos[1] - self.rect.top()) * self.yScale]
		return p

	# Returns the correct transform to use in the GraphWindow QGraphicsView
	def getTransform(self):

		self.update()

		t = QtGui.QTransform(1,0,0,-1,0,0)
		t.scale(self.xScale,self.yScale)
		return t

	# Returns the center of the view (call on the QGraphicsView centerOn)
	def getCenter(self):
		return self.rect.center()
Ejemplo n.º 35
0
 def boundingRect(self):
     return QRectF(0, 0, self.width, self.height)
Ejemplo n.º 36
0
	def __init__(self,graphicsView):
		self.scene = graphicsView.scene()
		self.gView = graphicsView
		self.rect = Rect(-1,1,2,2)
		self.update()
Ejemplo n.º 37
0
    def updateLeader(self):
        """
        TOWRITE
        """
        arrowStyle = Closed     # int # TODO: Make this customizable
        arrowStyleAngle = 15.0  # qreal # TODO: Make this customizable
        arrowStyleLength = 1.0  # qreal # TODO: Make this customizable
        self.lineStyleAngle = 45.0   # qreal # TODO: Make this customizable
        self.lineStyleLength = 1.0   # qreal # TODO: Make this customizable

        lyne = self.line()  # QLineF
        angle = lyne.angle()  # qreal
        ap0 = lyne.p1()  # QPointF
        lp0 = lyne.p2()  # QPointF

        # Arrow
        lynePerp = QLineF(lyne.pointAt(arrowStyleLength / lyne.length()), lp0)
        lynePerp.setAngle(angle + 90)
        lyne1 = QLineF(ap0, lp0)
        lyne2 = QLineF(ap0, lp0)
        lyne1.setAngle(angle + arrowStyleAngle)
        lyne2.setAngle(angle - arrowStyleAngle)
        # ap1 = QPointF()
        # ap2 = QPointF()
        _, ap1 = lynePerp.intersect(lyne1)
        _, ap2 = lynePerp.intersect(lyne2)

        # Math Diagram
        #                  .(ap1)                     .(lp1)
        #                 /|                         /|
        #                / |                        / |
        #               /  |                       /  |
        #              /   |                      /   |
        #             /    |                     /    |
        #            /     |                    /     |
        #           /      |                   /      |
        #          /       |                  /       |
        #         /+(aSA)  |                 /+(lSA)  |
        #  (ap0)./__(aSL)__|__________(lp0)./__(lSL)__|
        #        \ -(aSA)  |                \ -(lSA)  |
        #         \        |                 \        |
        #          \       |                  \       |
        #           \      |                   \      |
        #            \     |                    \     |
        #             \    |                     \    |
        #              \   |                      \   |
        #               \  |                       \  |
        #                \ |                        \ |
        #                 \|                         \|
        #                  .(ap2)                     .(lp2)

        if arrowStyle == Open:
            arrowStylePath = QPainterPath()
            arrowStylePath.moveTo(ap1)
            arrowStylePath.lineTo(ap0)
            arrowStylePath.lineTo(ap2)
            arrowStylePath.lineTo(ap0)
            arrowStylePath.lineTo(ap1)
        elif arrowStyle == Closed:
            arrowStylePath = QPainterPath()
            arrowStylePath.moveTo(ap1)
            arrowStylePath.lineTo(ap0)
            arrowStylePath.lineTo(ap2)
            arrowStylePath.lineTo(ap1)
        elif arrowStyle == Dot:
            arrowStylePath = QPainterPath()
            arrowStylePath.addEllipse(ap0, arrowStyleLength, arrowStyleLength)
        elif arrowStyle == Box:
            arrowStylePath = QPainterPath()
            side = QLineF(ap1, ap2).length()  # qreal
            ar0 = QRectF(0, 0, side, side)
            ar0.moveCenter(ap0)
            arrowStylePath.addRect(ar0)
        elif arrowStyle == Tick:
            pass  #TODO/PORT# Is this supposed to be empty?

        lineStylePath = QPainterPath()
        lineStylePath.moveTo(ap0)
        lineStylePath.lineTo(lp0)
Ejemplo n.º 38
0
class EmbDetailsDialog(QDialog):
    """
    Subclass of `QDialog`_

    Class implementing the Details dialog.

    .. sphinx_generate_methods_summary::
       EmbDetailsDialog
    """
    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()

    def __del__(self):
        """Class destructor"""
        QApplication.restoreOverrideCursor()

    def getInfo(self):
        """TOWRITE"""
        # TODO: generate a temporary pattern from the scene data.

        # TODO: grab this information from the pattern
        self.stitchesTotal = 5 # TODO: embStitchList_count(pattern->stitchList, TOTAL)
        self.stitchesReal  = 4 # TODO: embStitchList_count(pattern->stitchList, NORMAL)
        self.stitchesJump  = 3 # TODO: embStitchList_count(pattern->stitchList, JUMP)
        self.stitchesTrim  = 2 # TODO: embStitchList_count(pattern->stitchList, TRIM)
        self.colorTotal    = 1 # TODO: embThreadList_count(pattern->threadList, TOTAL)
        self.colorChanges  = 0 # TODO: embThreadList_count(pattern->threadList, CHANGES)

        self.boundingRect.setRect(0, 0, 50, 100) # TODO: embPattern_calcBoundingBox(pattern)

    def createMainWidget(self):
        """
        TOWRITE

        :return: TOWRITE
        :rtype: `QScrollArea`_
        """
        widget = QWidget(self)

        # Misc
        groupBoxMisc = QGroupBox(self.tr("General Information"), widget)

        labelStitchesTotal = QLabel(self.tr("Total Stitches:"), self)
        labelStitchesReal  = QLabel(self.tr("Real Stitches:"),  self)
        labelStitchesJump  = QLabel(self.tr("Jump Stitches:"),  self)
        labelStitchesTrim  = QLabel(self.tr("Trim Stitches:"),  self)
        labelColorTotal    = QLabel(self.tr("Total Colors:"),   self)
        labelColorChanges  = QLabel(self.tr("Color Changes:"),  self)
        labelRectLeft      = QLabel(self.tr("Left:"),           self)
        labelRectTop       = QLabel(self.tr("Top:"),            self)
        labelRectRight     = QLabel(self.tr("Right:"),          self)
        labelRectBottom    = QLabel(self.tr("Bottom:"),         self)
        labelRectWidth     = QLabel(self.tr("Width:"),          self)
        labelRectHeight    = QLabel(self.tr("Height:"),         self)

        fieldStitchesTotal = QLabel(u'%s' % (self.stitchesTotal), self)
        fieldStitchesReal  = QLabel(u'%s' % (self.stitchesReal),  self)
        fieldStitchesJump  = QLabel(u'%s' % (self.stitchesJump),  self)
        fieldStitchesTrim  = QLabel(u'%s' % (self.stitchesTrim),  self)
        fieldColorTotal    = QLabel(u'%s' % (self.colorTotal),    self)
        fieldColorChanges  = QLabel(u'%s' % (self.colorChanges),  self)
        fieldRectLeft      = QLabel(u'%s' % (str(self.boundingRect.left())   + " mm"), self)
        fieldRectTop       = QLabel(u'%s' % (str(self.boundingRect.top())    + " mm"), self)
        fieldRectRight     = QLabel(u'%s' % (str(self.boundingRect.right())  + " mm"), self)
        fieldRectBottom    = QLabel(u'%s' % (str(self.boundingRect.bottom()) + " mm"), self)
        fieldRectWidth     = QLabel(u'%s' % (str(self.boundingRect.width())  + " mm"), self)
        fieldRectHeight    = QLabel(u'%s' % (str(self.boundingRect.height()) + " mm"), self)

        gridLayoutMisc = QGridLayout(groupBoxMisc)
        gridLayoutMisc.addWidget(labelStitchesTotal,  0, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesReal,   1, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesJump,   2, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesTrim,   3, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelColorTotal,     4, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelColorChanges,   5, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectLeft,       6, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectTop,        7, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectRight,      8, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectBottom,     9, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectWidth,     10, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectHeight,    11, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesTotal,  0, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesReal,   1, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesJump,   2, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesTrim,   3, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldColorTotal,     4, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldColorChanges,   5, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectLeft,       6, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectTop,        7, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectRight,      8, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectBottom,     9, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectWidth,     10, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectHeight,    11, 1, Qt.AlignLeft)
        gridLayoutMisc.setColumnStretch(1,1)
        groupBoxMisc.setLayout(gridLayoutMisc)

        # TODO: Color Histogram

        # Stitch Distribution
        # groupBoxDist = QGroupBox(self.tr("Stitch Distribution"), widget)

        # TODO: Stitch Distribution Histogram

        # Widget Layout
        vboxLayoutMain = QVBoxLayout(widget)
        vboxLayoutMain.addWidget(groupBoxMisc)
        # vboxLayoutMain.addWidget(groupBoxDist)
        vboxLayoutMain.addStretch(1)
        widget.setLayout(vboxLayoutMain)

        scrollArea = QScrollArea(self)
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(widget)
        return scrollArea