Ejemplo n.º 1
0
 def foldInput(self, folded):
     self.element.paramsFolded = folded
     self.prepareGeometryChange()
     if self.element.algorithm.outputs:
         pt = self.getLinkPointForOutput(-1)
         pt = QPointF(0, pt.y())
         self.outButton.position = pt
     for arrow in self.arrows:
         arrow.updatePath()
     self.update()
Ejemplo n.º 2
0
 def foldInput(self, folded):
     self.element.setParametersCollapsed(folded)
     #also need to update the model's stored component
     self.model.childAlgorithm(self.element.childId()).setParametersCollapsed(folded)
     self.prepareGeometryChange()
     if self.element.algorithm().outputDefinitions():
         pt = self.getLinkPointForOutput(-1)
         pt = QPointF(0, pt.y())
         self.outButton.position = pt
     for arrow in self.arrows:
         arrow.updatePath()
     self.update()
Ejemplo n.º 3
0
 def paint(self, painter, option, widget=None):
     pt = QPointF(-math.floor(self.WIDTH / 2), -math.floor(self.HEIGHT / 2)) + self.position
     rect = QRectF(pt.x(), pt.y(), self.WIDTH, self.HEIGHT)
     if self.isIn:
         painter.setPen(QPen(Qt.transparent, 1))
         painter.setBrush(QBrush(QColor(55, 55, 55, 33),
                                 Qt.SolidPattern))
     else:
         painter.setPen(QPen(Qt.transparent, 1))
         painter.setBrush(QBrush(Qt.transparent,
                                 Qt.SolidPattern))
     painter.drawRect(rect)
     painter.drawPicture(pt.x(), pt.y(), self.picture)
Ejemplo n.º 4
0
 def paint(self, painter, option, widget=None):
     pt = QPointF(-self.WIDTH / 2, -self.HEIGHT / 2) + self.position
     rect = QRectF(pt.x(), pt.y(), self.WIDTH, self.HEIGHT)
     if self.isIn:
         painter.setPen(QPen(Qt.transparent, 1))
         painter.setBrush(QBrush(Qt.lightGray,
                                 Qt.SolidPattern))
     else:
         painter.setPen(QPen(Qt.transparent, 1))
         painter.setBrush(QBrush(Qt.transparent,
                                 Qt.SolidPattern))
     painter.drawRect(rect)
     painter.drawPixmap(pt.x(), pt.y(), self.pixmap)
Ejemplo n.º 5
0
    def __init__(self, element, model):
        super(ModelerGraphicItem, self).__init__(None)
        self.model = model
        self.element = element
        if isinstance(element, ModelerParameter):
            icon = QIcon(os.path.join(pluginPath, 'images', 'input.png'))
            self.pixmap = icon.pixmap(20, 20, state=QIcon.On)
            self.text = element.param.description
        elif isinstance(element, ModelerOutput):
            # Output name
            icon = QIcon(os.path.join(pluginPath, 'images', 'output.png'))
            self.pixmap = icon.pixmap(20, 20, state=QIcon.On)
            self.text = element.description
        else:
            self.text = element.description
            self.pixmap = element.algorithm.getIcon().pixmap(15, 15)
        self.arrows = []
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setZValue(1000)

        if not isinstance(element, ModelerOutput):
            icon = QIcon(os.path.join(pluginPath, 'images', 'edit.png'))
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2
                         - FlatButtonGraphicItem.WIDTH / 2,
                         ModelerGraphicItem.BOX_HEIGHT / 2
                         - FlatButtonGraphicItem.HEIGHT / 2 + 1)
            self.editButton = FlatButtonGraphicItem(icon, pt, self.editElement)
            self.editButton.setParentItem(self)
            icon = QIcon(os.path.join(pluginPath, 'images', 'delete.png'))
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2
                         - FlatButtonGraphicItem.WIDTH / 2,
                         - ModelerGraphicItem.BOX_HEIGHT / 2
                         + FlatButtonGraphicItem.HEIGHT / 2 + 1)
            self.deleteButton = FlatButtonGraphicItem(icon, pt,
                                                      self.removeElement)
            self.deleteButton.setParentItem(self)

        if isinstance(element, Algorithm):
            alg = element.algorithm
            if alg.parameters:
                pt = self.getLinkPointForParameter(-1)
                pt = QPointF(0, pt.y() + 2)
                self.inButton = FoldButtonGraphicItem(pt, self.foldInput, self.element.paramsFolded)
                self.inButton.setParentItem(self)
            if alg.outputs:
                pt = self.getLinkPointForOutput(-1)
                pt = QPointF(0, pt.y() + 2)
                self.outButton = FoldButtonGraphicItem(pt, self.foldOutput, self.element.outputsFolded)
                self.outButton.setParentItem(self)
Ejemplo n.º 6
0
    def testPagePositionToLayout(self):
        """
        Test pagePositionToLayoutPosition
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # invalid pages
        self.assertEqual(collection.pagePositionToLayoutPosition(-1, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(100, QgsLayoutPoint(1, 1)), QPointF(1, 1))

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        collection.addPage(page)

        #invalid pages
        self.assertEqual(collection.pagePositionToLayoutPosition(-1, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(1, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        #valid page
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(5, 6)), QPointF(5, 6))
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)), QPointF(50, 60))

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        #invalid pages
        self.assertEqual(collection.pagePositionToLayoutPosition(-1, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(3, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        #valid pages
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(1, 1)), QPointF(1, 1))
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(5, 6)), QPointF(5, 6))
        self.assertEqual(collection.pagePositionToLayoutPosition(0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)), QPointF(50, 60))
        self.assertEqual(collection.pagePositionToLayoutPosition(1, QgsLayoutPoint(1, 1)), QPointF(1, 308.0))
        self.assertEqual(collection.pagePositionToLayoutPosition(1, QgsLayoutPoint(5, 6)), QPointF(5, 313.0))
        self.assertEqual(collection.pagePositionToLayoutPosition(1, QgsLayoutPoint(0.5, 0.6, QgsUnitTypes.LayoutCentimeters)), QPointF(5, 313.0))
Ejemplo n.º 7
0
    def testQgsGradientFillSymbolLayer(self):
        """Test setting and getting QgsGradientFillSymbolLayer properties.
        """
        mGradientLayer = QgsGradientFillSymbolLayer()

        mExpectedValue = type(QgsGradientFillSymbolLayer())
        mValue = type(mGradientLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsGradientFillSymbolLayer.Radial
        mGradientLayer.setGradientType(mExpectedValue)
        mValue = mGradientLayer.gradientType()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsGradientFillSymbolLayer.ColorRamp
        mGradientLayer.setGradientColorType(mExpectedValue)
        mValue = mGradientLayer.gradientColorType()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QColor('#55aaff')
        mGradientLayer.setColor2(mExpectedValue)
        mValue = mGradientLayer.color2()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsGradientFillSymbolLayer.Viewport
        mGradientLayer.setCoordinateMode(mExpectedValue)
        mValue = mGradientLayer.coordinateMode()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsGradientFillSymbolLayer.Reflect
        mGradientLayer.setGradientSpread(mExpectedValue)
        mValue = mGradientLayer.gradientSpread()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QPointF(0.5, 0.8)
        mGradientLayer.setReferencePoint1(mExpectedValue)
        mValue = mGradientLayer.referencePoint1()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = True
        mGradientLayer.setReferencePoint1IsCentroid(mExpectedValue)
        mValue = mGradientLayer.referencePoint1IsCentroid()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QPointF(0.2, 0.4)
        mGradientLayer.setReferencePoint2(mExpectedValue)
        mValue = mGradientLayer.referencePoint2()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = True
        mGradientLayer.setReferencePoint2IsCentroid(mExpectedValue)
        mValue = mGradientLayer.referencePoint2IsCentroid()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 90
        mGradientLayer.setAngle(mExpectedValue)
        mValue = mGradientLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QPointF(10, 20)
        mGradientLayer.setOffset(mExpectedValue)
        mValue = mGradientLayer.offset()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsUnitTypes.RenderMapUnits
        mGradientLayer.setOffsetUnit(mExpectedValue)
        mValue = mGradientLayer.offsetUnit()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Ejemplo n.º 8
0
    def testPredictionPageNumberForPoint(self):
        """
        Test predictPageNumberForPoint
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # no crash if no pages
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(1, 1)), 0)

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize(QgsLayoutSize(100, 100))
        collection.addPage(page)

        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 350)), 3)

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize(QgsLayoutSize(100, 50))
        collection.addPage(page2)

        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 280)), 3)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 340)), 4)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 370)), 5)

        page3 = QgsLayoutItemPage(l)
        page3.setPageSize(QgsLayoutSize(100, 200))
        collection.addPage(page3)

        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 280)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 340)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 370)), 2)
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(-100, 470)), 3)
Ejemplo n.º 9
0
    def testPageAtPoint(self):
        """
        Test pageAtPoint
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        self.assertFalse(collection.pageAtPoint(QPointF(0, 0)))
        self.assertFalse(collection.pageAtPoint(QPointF(10, 10)))

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        collection.addPage(page)

        self.assertFalse(collection.pageAtPoint(QPointF(10, -1)))
        self.assertEqual(collection.pageAtPoint(QPointF(1, 1)), page)
        self.assertEqual(collection.pageAtPoint(QPointF(10, 10)), page)
        self.assertFalse(collection.pageAtPoint(QPointF(-10, 10)))
        self.assertFalse(collection.pageAtPoint(QPointF(1000, 10)))
        self.assertFalse(collection.pageAtPoint(QPointF(10, -10)))
        self.assertFalse(collection.pageAtPoint(QPointF(10, 1000)))

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        self.assertEqual(collection.pageAtPoint(QPointF(1, 1)), page)
        self.assertEqual(collection.pageAtPoint(QPointF(10, 10)), page)
        self.assertFalse(collection.pageAtPoint(QPointF(-10, 10)))
        self.assertFalse(collection.pageAtPoint(QPointF(1000, 10)))
        self.assertFalse(collection.pageAtPoint(QPointF(10, -10)))
        self.assertEqual(collection.pageAtPoint(QPointF(10, 330)), page2)
        self.assertEqual(collection.pageAtPoint(QPointF(10, 500)), page2)
        self.assertFalse(collection.pageAtPoint(QPointF(10, 600)))
Ejemplo n.º 10
0
    def testAddItemsFromXml(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        doc = QDomDocument("testdoc")
        # store in xml
        elem = l.writeXml(doc, QgsReadWriteContext())

        l2 = QgsLayout(p)
        new_items = l2.addItemsFromXml(elem, doc, QgsReadWriteContext())
        self.assertEqual(len(new_items), 2)
        items = l2.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        new_item1 = [i for i in items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.positionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))

        # test with a group
        group = QgsLayoutItemGroup(l)
        group.addItem(item1)
        group.addItem(item2)
        l.addLayoutItem(group)
        elem = l.writeXml(doc, QgsReadWriteContext())

        l3 = QgsLayout(p)
        new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext())
        self.assertEqual(len(new_items), 3)
        items = l3.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l3.items())
        self.assertTrue(new_items[1] in l3.items())
        self.assertTrue(new_items[2] in l3.items())

        # f*** you sip, I'll just manually cast
        new_group = sip.cast(l3.itemByUuid(group.uuid()), QgsLayoutItemGroup)
        self.assertIsNotNone(new_group)
        other_items = [i for i in new_items if i.type() != new_group.type()]
        self.assertCountEqual(new_group.items(), other_items)

        # test restoring at set position
        l3 = QgsLayout(p)
        new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30))
        self.assertEqual(len(new_items), 3)
        items = l3.items()
        new_item1 = [i for i in items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.positionWithUnits(), QgsLayoutPoint(10, 30, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.positionWithUnits(), QgsLayoutPoint(2.0, 4.0, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))

        # paste in place
        l4 = QgsLayout(p)
        page = QgsLayoutItemPage(l)
        page.setPageSize('A3')
        l4.pageCollection().addPage(page)
        page = QgsLayoutItemPage(l)
        page.setPageSize('A6')
        l4.pageCollection().addPage(page)

        new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30), True)
        self.assertEqual(len(new_items), 3)
        new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.page(), 0)
        self.assertEqual(new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.page(), 0)

        # paste in place, page 2
        new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 550), True)
        self.assertEqual(len(new_items), 3)
        new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.page(), 1)
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.page(), 1)
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
Ejemplo n.º 11
0
    def testPositionOnPage(self):
        """
        Test pageNumberForPoint and positionOnPage
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        collection.addPage(page)

        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 1)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 270)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 1270)), 0)

        self.assertEqual(collection.positionOnPage(QPointF(-100, -100)), QPointF(-100, -100))
        self.assertEqual(collection.positionOnPage(QPointF(-100, -1)), QPointF(-100, -1))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 1)), QPointF(-100, 1))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 270)), QPointF(-100, 270))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 1270)), QPointF(-100, 973))

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 1)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 270)), 0)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 370)), 1)
        self.assertEqual(collection.pageNumberForPoint(QPointF(-100, 1270)), 1)

        self.assertEqual(collection.positionOnPage(QPointF(-100, -100)), QPointF(-100, -100))
        self.assertEqual(collection.positionOnPage(QPointF(-100, -1)), QPointF(-100, -1))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 1)), QPointF(-100, 1))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 270)), QPointF(-100, 270))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 370)), QPointF(-100, 63))
        self.assertEqual(collection.positionOnPage(QPointF(-100, 1270)), QPointF(-100, 753))
Ejemplo n.º 12
0
    def testAppendPolyline(self):
        line = QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)])
        line2 = QPolygonF([QPointF(111, 12), QPointF(111, 12), QPointF(111, 14), QPointF(111, 15)])
        QgsSymbolLayerUtils.appendPolyline(line, line2)
        self.assertEqual([p for p in line],
                         [QPointF(11.0, 2.0), QPointF(11.0, 12.0), QPointF(111.0, 12.0), QPointF(111.0, 14.0),
                          QPointF(111.0, 15.0)])

        line = QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)])
        line2 = QPolygonF([QPointF(111, 14), QPointF(111, 15)])
        QgsSymbolLayerUtils.appendPolyline(line, line2)
        self.assertEqual([p for p in line],
                         [QPointF(11.0, 2.0), QPointF(11.0, 12.0), QPointF(111.0, 12.0), QPointF(111.0, 14.0),
                          QPointF(111.0, 15.0)])
Ejemplo n.º 13
0
    def canvasMoveEvent(self, mouseEvent):
        item = self.selectedItem()
        if not item:
            return

        annotation = item.annotation()
        if not annotation:
            return

        pixelToMmScale = 25.4 / self.canvas.logicalDpiX()
        if self.currentMoveAction == QgsMapCanvasAnnotationItem.MoveFramePosition:
            # move the entire frame
            newCanvasPos = item.pos() + (mouseEvent.pos() -
                                         self.lastMousePosition)
            if annotation.hasFixedMapPosition():
                deltaX = pixelToMmScale * (mouseEvent.pos().x() -
                                           self.lastMousePosition.x())
                deltaY = pixelToMmScale * (mouseEvent.pos().y() -
                                           self.lastMousePosition.y())
                annotation.setFrameOffsetFromReferencePointMm(
                    QPointF(
                        annotation.frameOffsetFromReferencePointMm().x() +
                        deltaX,
                        annotation.frameOffsetFromReferencePointMm().y() +
                        deltaY))
                annotation.setRelativePosition(
                    QPointF(newCanvasPos.x() / self.canvas.width(),
                            newCanvasPos.y() / self.canvas.height()))
                item.update()
                QgsProject.instance().setDirty(True)

        elif self.currentMoveAction != QgsMapCanvasAnnotationItem.NoAction:
            # handle vertical frame resize actions only
            size = annotation.frameSizeMm()
            xmin = annotation.frameOffsetFromReferencePointMm().x()
            ymin = annotation.frameOffsetFromReferencePointMm().y()
            xmax = xmin + size.width()
            ymax = ymin + size.height()
            relPosX = annotation.relativePosition().x()
            relPosY = annotation.relativePosition().y()

            if (self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameUp
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameLeftUp
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameRightUp):
                ymin += pixelToMmScale * (mouseEvent.pos().y() -
                                          self.lastMousePosition.y())
                relPosY = (relPosY * self.canvas.height() +
                           mouseEvent.pos().y() -
                           self.lastMousePosition.y()) / self.canvas.height()

            if (self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameDown
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameLeftDown
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameRightDown):
                ymax += pixelToMmScale * (mouseEvent.pos().y() -
                                          self.lastMousePosition.y())

            if (self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameLeft
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameLeftUp
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameLeftDown):
                xmin += pixelToMmScale * (mouseEvent.pos().x() -
                                          self.lastMousePosition.x())
                relPosX = (relPosX * self.canvas.width() +
                           mouseEvent.pos().x() -
                           self.lastMousePosition.x()) / self.canvas.width()

            if (self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameRight
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameRightUp
                    or self.currentMoveAction
                    == QgsMapCanvasAnnotationItem.ResizeFrameRightDown):
                xmax += pixelToMmScale * (mouseEvent.pos().x() -
                                          self.lastMousePosition.x())

            # switch min / max if necessary
            if xmax < xmin:
                tmp = xmax
                xmax = xmin
                xmin = tmp
            if ymax < ymin:
                tmp = ymax
                ymax = ymin
                ymin = tmp
            annotation.setFrameOffsetFromReferencePointMm(QPointF(xmin, ymin))
            annotation.setFrameSizeMm(QSizeF(xmax - xmin, ymax - ymin))
            annotation.setRelativePosition(QPointF(relPosX, relPosY))
            item.update()
            QgsProject.instance().setDirty(True)

        moveAction = item.moveActionForPosition(mouseEvent.pos())
        cursor = QCursor()
        cursor.setShape(item.cursorShapeForAction(moveAction))
        self.setCursor(cursor)

        self.lastMousePosition = mouseEvent.pos()
Ejemplo n.º 14
0
    def paint(self, painter, option, widget=None):
        rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2.0,
                      -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2.0,
                      ModelerGraphicItem.BOX_WIDTH + 2,
                      ModelerGraphicItem.BOX_HEIGHT + 2)

        if isinstance(self.element, QgsProcessingModelParameter):
            color = QColor(238, 242, 131)
            stroke = QColor(234, 226, 118)
            selected = QColor(116, 113, 68)
        elif isinstance(self.element, QgsProcessingModelChildAlgorithm):
            color = QColor(255, 255, 255)
            stroke = Qt.gray
            selected = QColor(50, 50, 50)
        else:
            color = QColor(172, 196, 114)
            stroke = QColor(90, 140, 90)
            selected = QColor(42, 65, 42)
        if self.isSelected():
            stroke = selected
            color = color.darker(110)
        painter.setPen(QPen(stroke, 0))  # 0 width "cosmetic" pen
        painter.setBrush(QBrush(color, Qt.SolidPattern))
        painter.drawRect(rect)
        font = QFont('Verdana', 8)
        font.setPixelSize(12)
        painter.setFont(font)
        painter.setPen(QPen(Qt.black))
        text = self.getAdjustedText(self.text)
        if isinstance(self.element, QgsProcessingModelChildAlgorithm
                      ) and not self.element.isActive():
            painter.setPen(QPen(Qt.gray))
            text = text + "\n(deactivated)"
        fm = QFontMetricsF(font)
        text = self.getAdjustedText(self.text)
        h = fm.ascent()
        pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25,
                     ModelerGraphicItem.BOX_HEIGHT / 2.0 - h + 1)
        painter.drawText(pt, text)
        painter.setPen(QPen(Qt.black))
        if isinstance(self.element, QgsProcessingModelChildAlgorithm):
            h = -(fm.height() * 1.2)
            h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
            pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
            painter.drawText(pt, 'In')
            i = 1
            if not self.element.parametersCollapsed():
                for param in [
                        p for p in
                        self.element.algorithm().parameterDefinitions()
                        if not p.isDestination()
                ]:
                    if not param.flags(
                    ) & QgsProcessingParameterDefinition.FlagHidden:
                        text = self.getAdjustedText(param.description())
                        h = -(fm.height() * 1.2) * (i + 1)
                        h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
                        pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                        painter.drawText(pt, text)
                        i += 1
            h = fm.height() * 1.1
            h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
            pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
            painter.drawText(pt, 'Out')
            if not self.element.outputsCollapsed():
                for i, out in enumerate(
                        self.element.algorithm().outputDefinitions()):
                    text = self.getAdjustedText(out.description())
                    h = fm.height() * 1.2 * (i + 2)
                    h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
                    pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                    painter.drawText(pt, text)
        if self.pixmap:
            painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8,
                               self.pixmap)
        elif self.picture:
            painter.drawPicture(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8,
                                self.picture)
Ejemplo n.º 15
0
    def __init__(self, element, model, controls, scene=None):
        super(ModelerGraphicItem, self).__init__(None)
        self.controls = controls
        self.model = model
        self.scene = scene
        self.element = element
        if isinstance(element, QgsProcessingModelParameter):
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'input.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            paramDef = self.model.parameterDefinition(element.parameterName())
            if paramDef:
                self.text = paramDef.description()
            else:
                self.text = 'Error ({})'.format(element.parameterName())
        elif isinstance(element, QgsProcessingModelOutput):
            # Output name
            svg = QSvgRenderer(os.path.join(pluginPath, 'images',
                                            'output.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.name()
        else:
            if element.algorithm().svgIconPath():
                svg = QSvgRenderer(element.algorithm().svgIconPath())
                size = svg.defaultSize()
                self.picture = QPicture()
                painter = QPainter(self.picture)
                painter.scale(16 / size.width(), 16 / size.width())
                svg.render(painter)
                self.pixmap = None
            else:
                self.pixmap = element.algorithm().icon().pixmap(15, 15)
            self.text = element.description()
        self.arrows = []
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setZValue(1000)

        if controls:
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'edit.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(
                ModelerGraphicItem.BOX_WIDTH / 2 -
                FlatButtonGraphicItem.WIDTH / 2,
                ModelerGraphicItem.BOX_HEIGHT / 2 -
                FlatButtonGraphicItem.HEIGHT / 2)
            self.editButton = FlatButtonGraphicItem(picture, pt,
                                                    self.editElement)
            self.editButton.setParentItem(self)
            svg = QSvgRenderer(os.path.join(pluginPath, 'images',
                                            'delete.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(
                ModelerGraphicItem.BOX_WIDTH / 2 -
                FlatButtonGraphicItem.WIDTH / 2,
                FlatButtonGraphicItem.HEIGHT / 2 -
                ModelerGraphicItem.BOX_HEIGHT / 2)
            self.deleteButton = FlatButtonGraphicItem(picture, pt,
                                                      self.removeElement)
            self.deleteButton.setParentItem(self)

        if isinstance(element, QgsProcessingModelChildAlgorithm):
            alg = element.algorithm()
            if [
                    a for a in alg.parameterDefinitions()
                    if not a.isDestination()
            ]:
                pt = self.getLinkPointForParameter(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.inButton = FoldButtonGraphicItem(
                        pt, self.foldInput, self.element.parametersCollapsed())
                    self.inButton.setParentItem(self)
            if alg.outputDefinitions():
                pt = self.getLinkPointForOutput(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.outButton = FoldButtonGraphicItem(
                        pt, self.foldOutput, self.element.outputsCollapsed())
                    self.outButton.setParentItem(self)
Ejemplo n.º 16
0
    def __init__(self, element, model, controls):
        super(ModelerGraphicItem, self).__init__(None)
        self.controls = controls
        self.model = model
        self.element = element
        if isinstance(element, ModelerParameter):
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'input.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.param.description
        elif isinstance(element, ModelerOutput):
            # Output name
            svg = QSvgRenderer(os.path.join(pluginPath, 'images',
                                            'output.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.description
        else:
            self.text = element.description
            self.pixmap = element.algorithm.getIcon().pixmap(15, 15)
        self.arrows = []
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setZValue(1000)

        if not isinstance(element, ModelerOutput) and controls:
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'edit.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(
                ModelerGraphicItem.BOX_WIDTH / 2 -
                FlatButtonGraphicItem.WIDTH / 2,
                ModelerGraphicItem.BOX_HEIGHT / 2 -
                FlatButtonGraphicItem.HEIGHT / 2)
            self.editButton = FlatButtonGraphicItem(picture, pt,
                                                    self.editElement)
            self.editButton.setParentItem(self)
            svg = QSvgRenderer(os.path.join(pluginPath, 'images',
                                            'delete.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(
                ModelerGraphicItem.BOX_WIDTH / 2 -
                FlatButtonGraphicItem.WIDTH / 2,
                FlatButtonGraphicItem.HEIGHT / 2 -
                ModelerGraphicItem.BOX_HEIGHT / 2)
            self.deleteButton = FlatButtonGraphicItem(picture, pt,
                                                      self.removeElement)
            self.deleteButton.setParentItem(self)

        if isinstance(element, Algorithm):
            alg = element.algorithm
            if alg.parameters:
                pt = self.getLinkPointForParameter(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.inButton = FoldButtonGraphicItem(
                        pt, self.foldInput, self.element.paramsFolded)
                    self.inButton.setParentItem(self)
            if alg.outputs:
                pt = self.getLinkPointForOutput(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.outButton = FoldButtonGraphicItem(
                        pt, self.foldOutput, self.element.outputsFolded)
                    self.outButton.setParentItem(self)
Ejemplo n.º 17
0
    def updatePath(self):
        self.endPoints = []
        controlPoints = []
        endPt = self.endItem.getLinkPointForParameter(self.endIndex)
        if isinstance(self.startItem.element,
                      QgsProcessingModelAlgorithm.ModelParameter):
            startPt = self.startItem.getLinkPointForParameter(self.startIndex)
        else:
            startPt = self.startItem.getLinkPointForOutput(self.startIndex)
        if isinstance(self.endItem.element,
                      QgsProcessingModelAlgorithm.ModelParameter):
            endPt = self.endItem.getLinkPointForParameter(self.startIndex)

        if isinstance(self.startItem.element,
                      QgsProcessingModelAlgorithm.ChildAlgorithm):
            if self.startIndex != -1:
                controlPoints.append(self.startItem.pos() + startPt)
                controlPoints.append(self.startItem.pos() + startPt +
                                     QPointF(ModelerGraphicItem.BOX_WIDTH /
                                             3, 0))
                controlPoints.append(self.endItem.pos() + endPt -
                                     QPointF(ModelerGraphicItem.BOX_WIDTH /
                                             3, 0))
                controlPoints.append(self.endItem.pos() + endPt)
                pt = QPointF(self.startItem.pos() + startPt + QPointF(-3, -3))
                self.endPoints.append(pt)
                pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3))
                self.endPoints.append(pt)
            else:
                # Case where there is a dependency on an algorithm not
                # on an output
                controlPoints.append(self.startItem.pos() + startPt)
                controlPoints.append(self.startItem.pos() + startPt +
                                     QPointF(ModelerGraphicItem.BOX_WIDTH /
                                             3, 0))
                controlPoints.append(self.endItem.pos() + endPt -
                                     QPointF(ModelerGraphicItem.BOX_WIDTH /
                                             3, 0))
                controlPoints.append(self.endItem.pos() + endPt)
        else:
            controlPoints.append(self.startItem.pos())
            controlPoints.append(self.startItem.pos() +
                                 QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0))
            controlPoints.append(self.endItem.pos() + endPt -
                                 QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0))
            controlPoints.append(self.endItem.pos() + endPt)
            pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3))
            self.endPoints.append(pt)
        path = QPainterPath()
        path.moveTo(controlPoints[0])
        path.cubicTo(*controlPoints[1:])
        self.setPath(path)
Ejemplo n.º 18
0
    def testLayoutItemAt(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemMap(l)
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)

        item2 = QgsLayoutItemMap(l)
        item2.attemptMove(QgsLayoutPoint(6, 10, QgsUnitTypes.LayoutMillimeters))
        item2.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item2)

        item3 = QgsLayoutItemMap(l)
        item3.attemptMove(QgsLayoutPoint(8, 12, QgsUnitTypes.LayoutMillimeters))
        item3.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        item3.setLocked(True)
        l.addItem(item3)

        self.assertIsNone(l.layoutItemAt(QPointF(0, 0)))
        self.assertIsNone(l.layoutItemAt(QPointF(100, 100)))

        self.assertEqual(l.layoutItemAt(QPointF(5, 9)), item1)
        self.assertEqual(l.layoutItemAt(QPointF(25, 23)), item3)
        self.assertIsNone(l.layoutItemAt(QPointF(25, 23), True))
        self.assertEqual(l.layoutItemAt(QPointF(7, 11)), item2)
        self.assertEqual(l.layoutItemAt(QPointF(9, 13)), item3)
        self.assertEqual(l.layoutItemAt(QPointF(9, 13), True), item2)

        self.assertEqual(l.layoutItemAt(QPointF(9, 13), item3), item2)
        self.assertEqual(l.layoutItemAt(QPointF(9, 13), item2), item1)
        self.assertIsNone(l.layoutItemAt(QPointF(9, 13), item1))
        item2.setLocked(True)
        self.assertEqual(l.layoutItemAt(QPointF(9, 13), item3, True), item1)
    def drawHistogram(self):
        #if self.inputlayer is None:
        #    return
        self.showInfo("Drawing histogram...")
        viewprect = QRectF(self.histoGraphicsView.viewport().rect())
        self.histoGraphicsView.setSceneRect(viewprect)
        self.setupScene.clear()
        self.setupScene.update()
        histbottom = self.histoGraphicsView.sceneRect().bottom()
        histtop = self.histoGraphicsView.sceneRect().top()
        left = self.histoGraphicsView.sceneRect().left() + self.histopadding
        right = self.histoGraphicsView.sceneRect().right() - self.histopadding
        histheight = histbottom - histtop
        histwidth = right - left
        step = 1.0 * histwidth / self.histobins
        maxlength = histheight
        padding = 1
        ll = QPoint(self.histopadding - 1, histheight - padding)
        start = QPointF(self.histoGraphicsView.mapToScene(ll))

        # Check if there is only one value
        #myrange = (self.minValueSpinBox.value(),self.maxValueSpinBox.value())
        if self.histogramAvailable:
            maxvalue = 0.0
            for i in range(len(self.histo[0])):
                if self.histo[0][i] > maxvalue:
                    maxvalue = self.histo[0][i]
            if maxvalue == 0:
                return
            self.maxBinNumber.setText(str(maxvalue))
            # Create the histogram:
            #self.showInfo("maxvalue: " + str(maxvalue))
            #self.showInfo("maxlength: " + str(maxlength))
            #self.showInfo("step: " + str(step))
            for i in range(self.histobins):
                binnumber = self.histo[0][i]
                if binnumber == 0:
                    continue
                height = (1.0 * self.histo[0][i] / maxvalue *
                                          (maxlength - padding))
                rectangle = QGraphicsRectItem(start.x() + step * i,
                                          start.y(),
                                          step,
                                          -height)
                rectangle.setPen(QPen(QColor(102, 102, 102)))
                rectangle.setBrush(QBrush(QColor(240, 240, 240)))
                self.setupScene.addItem(rectangle)
                #self.showInfo(str(i) + ": " + str(height))
            #if self.levelsListView.model().rowCount() > 0:
        # Add lines for the levels
        minvalue = float(self.histMinValue.text())
        maxvalue = float(self.histMaxValue.text())
        datarange = maxvalue - minvalue
        if datarange == 0:
            return
        i = 0
        while self.levelsListView.model().item(i):
            #self.showInfo("Element: " +
            #       str(self.levelsListView.model().item(i).text()))
            #continue
            value = float(self.levelsListView.model().item(i).text())
            xvalue = start.x() + histwidth * (value - minvalue) / datarange
            line = QGraphicsLineItem(xvalue, 0, xvalue, histheight)
            if i == 0 or i == (self.levelsListView.model().rowCount() - 1):
                line.setPen(QPen(QColor(204, 0, 0)))
            else:
                line.setPen(QPen(QColor(0, 204, 0)))
            self.setupScene.addItem(line)
            i = i + 1
Ejemplo n.º 20
0
    def testPolylineSubstring(self):
        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF(), 1, 2)  # no crash
        self.assertFalse(res)

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF(), -1, 2)  # no crash
        self.assertFalse(res)

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF(), 1, -2)  # no crash
        self.assertFalse(res)

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF(), -1, -2)  # no crash
        self.assertFalse(res)

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 0,
                                                    -110)
        self.assertEqual([p for p in res], [])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 0,
                                                    110)
        self.assertEqual([p for p in res], [QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), -1,
                                                    -1000)
        self.assertFalse([p for p in res])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    -1000)
        self.assertFalse([p for p in res])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), -1,
                                                    1000)
        self.assertEqual([p for p in res], [QPointF(110.0, 12.0), QPointF(111.0, 12.0)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]),
                                                    100000, -10000)
        self.assertFalse([p for p in res])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    -109)
        self.assertEqual([p for p in res], [])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    109)
        self.assertEqual([p for p in res], [QPointF(11.0, 3.0), QPointF(11.0, 12.0), QPointF(110.0, 12.0)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]),
                                                    -109, 109)
        self.assertEqual([p for p in res], [QPointF(11.0, 3.0), QPointF(11.0, 12.0), QPointF(110.0, 12.0)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    -1000)
        self.assertEqual([p for p in res], [])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    10)
        self.assertEqual([p for p in res], [QPointF(11, 3), QPointF(11, 12)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    0)
        self.assertEqual([p for p in res], [QPointF(11, 3), QPointF(11, 12), QPointF(111, 12)])

        res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)]), 1,
                                                    -90)
        self.assertEqual([p for p in res], [QPointF(11, 3), QPointF(11, 12), QPointF(21, 12)])
Ejemplo n.º 21
0
    def __init__(self, element, model, controls):
        super(ModelerGraphicItem, self).__init__(None)
        self.controls = controls
        self.model = model
        self.element = element
        if isinstance(element, ModelerParameter):
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'input.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.param.description
        elif isinstance(element, ModelerOutput):
            # Output name
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'output.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.description
        else:
            self.text = element.description
            self.pixmap = element.algorithm.getIcon().pixmap(15, 15)
        self.arrows = []
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setZValue(1000)

        if not isinstance(element, ModelerOutput) and controls:
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'edit.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2
                         - FlatButtonGraphicItem.WIDTH / 2,
                         ModelerGraphicItem.BOX_HEIGHT / 2
                         - FlatButtonGraphicItem.HEIGHT / 2)
            self.editButton = FlatButtonGraphicItem(picture, pt, self.editElement)
            self.editButton.setParentItem(self)
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'delete.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2
                         - FlatButtonGraphicItem.WIDTH / 2,
                         - ModelerGraphicItem.BOX_HEIGHT / 2
                         + FlatButtonGraphicItem.HEIGHT / 2)
            self.deleteButton = FlatButtonGraphicItem(picture, pt,
                                                      self.removeElement)
            self.deleteButton.setParentItem(self)

        if isinstance(element, Algorithm):
            alg = element.algorithm
            if alg.parameters:
                pt = self.getLinkPointForParameter(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.inButton = FoldButtonGraphicItem(pt, self.foldInput, self.element.paramsFolded)
                    self.inButton.setParentItem(self)
            if alg.outputs:
                pt = self.getLinkPointForOutput(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.outButton = FoldButtonGraphicItem(pt, self.foldOutput, self.element.outputsFolded)
                    self.outButton.setParentItem(self)
Ejemplo n.º 22
0
    def fromOldFormatFile(filename):
        def _tr(s):
            return QCoreApplication.translate('ModelerAlgorithm', s)
        hardcodedValues = {}
        modelParameters = []
        modelAlgs = []
        model = ModelerAlgorithm()
        model.descriptionFile = filename
        lines = codecs.open(filename, 'r', encoding='utf-8')
        line = lines.readline().strip('\n').strip('\r')
        try:
            while line != '':
                if line.startswith('PARAMETER:'):
                    paramLine = line[len('PARAMETER:'):]
                    param = getParameterFromString(paramLine)
                    if param:
                        pass
                    else:
                        raise WrongModelException(
                            _tr('Error in parameter line: %s', 'ModelerAlgorithm') % line)
                    line = lines.readline().strip('\n')
                    tokens = line.split(',')
                    model.addParameter(ModelerParameter(param,
                                                        QPointF(float(tokens[0]), float(tokens[1]))))
                    modelParameters.append(param.name)
                elif line.startswith('VALUE:'):
                    valueLine = line[len('VALUE:'):]
                    tokens = valueLine.split('===')
                    name = tokens[0]
                    value = tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING, '\n')
                    hardcodedValues[name] = value
                elif line.startswith('NAME:'):
                    model.name = line[len('NAME:'):]
                elif line.startswith('GROUP:'):
                    model.group = line[len('GROUP:'):]
                elif line.startswith('ALGORITHM:'):
                    algLine = line[len('ALGORITHM:'):]
                    alg = algList.getAlgorithm(algLine)
                    if alg is not None:
                        modelAlg = Algorithm(alg.commandLineName())
                        modelAlg.description = alg.name
                        posline = lines.readline().strip('\n').strip('\r')
                        tokens = posline.split(',')
                        modelAlg.pos = QPointF(float(tokens[0]), float(tokens[1]))
                        # dependenceline = lines.readline().strip('\n').strip('\r')
                        for param in alg.parameters:
                            if not param.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if line == unicode(None):
                                    modelAlg.params[param.name] = None
                                else:
                                    tokens = line.split('|')
                                    try:
                                        algIdx = int(tokens[0])
                                    except:
                                        raise WrongModelException(
                                            _tr('Number of parameters in the '
                                                '{} algorithm does not match '
                                                'current Processing '
                                                'implementation'.format(alg.name)))
                                    if algIdx == -1:
                                        if tokens[1] in modelParameters:
                                            modelAlg.params[param.name] = ValueFromInput(tokens[1])
                                        else:
                                            modelAlg.params[param.name] = hardcodedValues[tokens[1]]
                                    else:
                                        modelAlg.params[param.name] = ValueFromOutput(algIdx, tokens[1])

                        for out in alg.outputs:
                            if not out.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if unicode(None) != line:
                                    if '|' in line:
                                        tokens = line.split('|')
                                        name = tokens[0]
                                        tokens = tokens[1].split(',')
                                        pos = QPointF(float(tokens[0]), float(tokens[1]))
                                    else:
                                        name = line
                                        pos = None
                                    modelerOutput = ModelerOutput(name)
                                    modelerOutput.pos = pos
                                    modelAlg.outputs[out.name] = modelerOutput

                        model.addAlgorithm(modelAlg)
                        modelAlgs.append(modelAlg.name)
                    else:
                        raise WrongModelException(
                            _tr('Error in algorithm name: %s',) % algLine)
                line = lines.readline().strip('\n').strip('\r')
            for modelAlg in model.algs.values():
                for name, value in modelAlg.params.iteritems():
                    if isinstance(value, ValueFromOutput):
                        value.alg = modelAlgs[value.alg]
            return model
        except Exception as e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException(_tr('Error in model definition line: ') + '%s\n%s' % (line.strip(), traceback.format_exc()))
Ejemplo n.º 23
0
    def paintModel(self, model, controls=True):
        self.model = model
        context = createContext()
        # Inputs
        for inp in list(model.parameterComponents().values()):
            item = ModelerGraphicItem(inp, model, controls, scene=self)
            item.setFlag(QGraphicsItem.ItemIsMovable, True)
            item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(item)
            item.setPos(inp.position().x(), inp.position().y())
            self.paramItems[inp.parameterName()] = item

        # Input dependency arrows
        for input_name in list(model.parameterComponents().keys()):
            idx = 0
            parameter_def = model.parameterDefinition(input_name)
            parent_name = None
            if hasattr(parameter_def, 'parentLayerParameterName') and parameter_def.parentLayerParameterName():
                parent_name = parameter_def.parentLayerParameterName()
            elif hasattr(parameter_def, 'parentParameterName') and parameter_def.parentParameterName():
                parent_name = parameter_def.parentParameterName()
            if parent_name:
                if input_name in self.paramItems and parent_name in self.paramItems:
                    input_item = self.paramItems[input_name]
                    parent_item = self.paramItems[parent_name]
                    arrow = ModelerArrowItem(parent_item, -1, input_item, -1)
                    input_item.addArrow(arrow)
                    parent_item.addArrow(arrow)
                    arrow.setPenStyle(Qt.DotLine)
                    arrow.updatePath()
                    self.addItem(arrow)

        # We add the algs
        for alg in list(model.childAlgorithms().values()):
            item = ModelerGraphicItem(alg, model, controls, scene=self)
            item.setFlag(QGraphicsItem.ItemIsMovable, True)
            item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(item)
            item.setPos(alg.position().x(), alg.position().y())
            self.algItems[alg.childId()] = item

        # And then the arrows

        for alg in list(model.childAlgorithms().values()):
            idx = 0
            for parameter in alg.algorithm().parameterDefinitions():
                if not parameter.isDestination() and not parameter.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    if parameter.name() in alg.parameterSources():
                        sources = alg.parameterSources()[parameter.name()]
                    else:
                        sources = []
                    for source in sources:
                        sourceItems = self.getItemsFromParamValue(source, alg.childId(), context)
                        for sourceItem, sourceIdx in sourceItems:
                            arrow = ModelerArrowItem(sourceItem, sourceIdx, self.algItems[alg.childId()], idx)
                            sourceItem.addArrow(arrow)
                            self.algItems[alg.childId()].addArrow(arrow)
                            arrow.updatePath()
                            self.addItem(arrow)
                        idx += 1
            for depend in alg.dependencies():
                arrow = ModelerArrowItem(self.algItems[depend], -1,
                                         self.algItems[alg.childId()], -1)
                self.algItems[depend].addArrow(arrow)
                self.algItems[alg.childId()].addArrow(arrow)
                arrow.updatePath()
                self.addItem(arrow)

        # And finally the outputs
        for alg in list(model.childAlgorithms().values()):
            outputs = alg.modelOutputs()
            outputItems = {}
            idx = 0
            for key, out in outputs.items():
                if out is not None:
                    item = ModelerGraphicItem(out, model, controls, scene=self)
                    item.setFlag(QGraphicsItem.ItemIsMovable, True)
                    item.setFlag(QGraphicsItem.ItemIsSelectable, True)
                    self.addItem(item)
                    pos = out.position()
                    if pos is None:
                        pos = (alg.position() + QPointF(ModelerGraphicItem.BOX_WIDTH, 0) +
                               self.algItems[alg.childId()].getLinkPointForOutput(idx))
                    item.setPos(pos)
                    outputItems[key] = item
                    arrow = ModelerArrowItem(self.algItems[alg.childId()], idx, item,
                                             -1)
                    self.algItems[alg.childId()].addArrow(arrow)
                    item.addArrow(arrow)
                    arrow.updatePath()
                    self.addItem(arrow)
                    idx += 1
                else:
                    outputItems[key] = None
            self.outputItems[alg.childId()] = outputItems
Ejemplo n.º 24
0
    def paintModel(self, model):
        self.model = model
        # Inputs
        for inp in list(model.inputs.values()):
            item = ModelerGraphicItem(inp, model)
            item.setFlag(QGraphicsItem.ItemIsMovable, True)
            item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(item)
            item.setPos(inp.pos.x(), inp.pos.y())
            self.paramItems[inp.param.name] = item

        # We add the algs
        for alg in list(model.algs.values()):
            item = ModelerGraphicItem(alg, model)
            item.setFlag(QGraphicsItem.ItemIsMovable, True)
            item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(item)
            item.setPos(alg.pos.x(), alg.pos.y())
            self.algItems[alg.name] = item

        # And then the arrows
        for alg in list(model.algs.values()):
            idx = 0
            for parameter in alg.algorithm.parameters:
                if not parameter.hidden:
                    if parameter.name in alg.params:
                        value = alg.params[parameter.name]
                    else:
                        value = None
                    sourceItems = self.getItemsFromParamValue(value)
                    for sourceItem, sourceIdx in sourceItems:
                        arrow = ModelerArrowItem(sourceItem, sourceIdx,
                                                 self.algItems[alg.name], idx)
                        sourceItem.addArrow(arrow)
                        self.algItems[alg.name].addArrow(arrow)
                        arrow.updatePath()
                        self.addItem(arrow)
                    idx += 1
            for depend in alg.dependencies:
                arrow = ModelerArrowItem(self.algItems[depend], -1,
                                         self.algItems[alg.name], -1)
                self.algItems[depend].addArrow(arrow)
                self.algItems[alg.name].addArrow(arrow)
                arrow.updatePath()
                self.addItem(arrow)

        # And finally the outputs
        for alg in list(model.algs.values()):
            outputs = alg.outputs
            outputItems = {}
            idx = 0
            for key in outputs:
                out = outputs[key]
                if out is not None:
                    item = ModelerGraphicItem(out, model)
                    item.setFlag(QGraphicsItem.ItemIsMovable, True)
                    item.setFlag(QGraphicsItem.ItemIsSelectable, True)
                    self.addItem(item)
                    pos = alg.outputs[key].pos
                    if pos is None:
                        pos = (
                            alg.pos +
                            QPointF(ModelerGraphicItem.BOX_WIDTH, 0) +
                            self.algItems[alg.name].getLinkPointForOutput(idx))
                    item.setPos(pos)
                    outputItems[key] = item
                    arrow = ModelerArrowItem(self.algItems[alg.name], idx,
                                             item, -1)
                    self.algItems[alg.name].addArrow(arrow)
                    item.addArrow(arrow)
                    arrow.updatePath()
                    self.addItem(arrow)
                    idx += 1
                else:
                    outputItems[key] = None
            self.outputItems[alg.name] = outputItems
Ejemplo n.º 25
0
    def testSnapPoint(self):
        p = QgsProject()
        l = QgsLayout(p)
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        l.pageCollection().addPage(page)
        s = QgsLayoutSnapper(l)
        guides = l.guides()

        # first test snapping to grid
        l.gridSettings().setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutMillimeters))
        s.setSnapToGrid(True)
        s.setSnapTolerance(1)

        point, snapped = s.snapPoint(QPointF(1, 1), 1)
        self.assertTrue(snapped)
        self.assertEqual(point, QPointF(0, 0))

        s.setSnapToItems(False)
        s.setSnapToGrid(False)
        point, snapped = s.snapPoint(QPointF(1, 1), 1)
        self.assertFalse(snapped)
        self.assertEqual(point, QPointF(1, 1))

        # test that guide takes precedence
        s.setSnapToGrid(True)
        s.setSnapToGuides(True)
        guides.addGuide(QgsLayoutGuide(Qt.Horizontal, QgsLayoutMeasurement(0.5), page))
        point, snapped = s.snapPoint(QPointF(1, 1), 1)
        self.assertTrue(snapped)
        self.assertEqual(point, QPointF(0, 0.5))

        # add an item
        item1 = QgsLayoutItemMap(l)
        item1.attemptMove(QgsLayoutPoint(121, 1.1, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)

        # test that guide takes precedence over item
        s.setSnapToGrid(True)
        s.setSnapToGuides(True)
        s.setSnapToItems(True)
        point, snapped = s.snapPoint(QPointF(1, 1), 1)
        self.assertTrue(snapped)
        self.assertEqual(point, QPointF(0, 0.5))
        # but items take precedence over grid
        s.setSnapToGuides(False)
        point, snapped = s.snapPoint(QPointF(1, 1), 1)
        self.assertTrue(snapped)
        self.assertEqual(point, QPointF(0, 1.1))

        # ... unless item is ignored!
        point, snapped = s.snapPoint(QPointF(1, 1), 1, None, None, [item1])
        self.assertTrue(snapped)
        self.assertEqual(point, QPointF(0, 0))
Ejemplo n.º 26
0
    def testSnapPointToGrid(self):
        p = QgsProject()
        l = QgsLayout(p)
        # need a page to snap to grid
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        l.pageCollection().addPage(page)
        s = QgsLayoutSnapper(l)

        l.gridSettings().setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutMillimeters))

        s.setSnapToGrid(True)
        s.setSnapTolerance(1)

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(1, 1), 1)
        self.assertTrue(snappedX)
        self.assertTrue(snappedY)
        self.assertEqual(point, QPointF(0, 0))

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(9, 1), 1)
        self.assertTrue(snappedX)
        self.assertTrue(snappedY)
        self.assertEqual(point, QPointF(10, 0))

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(1, 11), 1)
        self.assertTrue(snappedX)
        self.assertTrue(snappedY)
        self.assertEqual(point, QPointF(0, 10))

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 11), 1)
        self.assertFalse(snappedX)
        self.assertTrue(snappedY)
        self.assertEqual(point, QPointF(13, 10))

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(11, 13), 1)
        self.assertTrue(snappedX)
        self.assertFalse(snappedY)
        self.assertEqual(point, QPointF(10, 13))

        point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 23), 1)
        self.assertFalse(snappedX)
        self.assertFalse(snappedY)
        self.assertEqual(point, QPointF(13, 23))

        # grid disabled
        s.setSnapToGrid(False)
        point, nappedX, snappedY = s.snapPointToGrid(QPointF(1, 1), 1)
        self.assertFalse(nappedX)
        self.assertFalse(snappedY)
        self.assertEqual(point, QPointF(1, 1))
        s.setSnapToGrid(True)

        # with different pixel scale
        point, snappedX, snappedY = s.snapPointToGrid(QPointF(0.5, 0.5), 1)
        self.assertTrue(snappedX)
        self.assertTrue(snappedY)
        self.assertEqual(point, QPointF(0, 0))
        point, snappedX, snappedY = s.snapPointToGrid(QPointF(0.5, 0.5), 3)
        self.assertFalse(snappedX)
        self.assertFalse(snappedY)
        self.assertEqual(point, QPointF(0.5, 0.5))

        # with offset grid
        l.gridSettings().setOffset(QgsLayoutPoint(2, 0))
        point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 23), 1)
        self.assertTrue(snappedX)
        self.assertFalse(snappedY)
        self.assertEqual(point, QPointF(12, 23))
Ejemplo n.º 27
0
    def __init__(self, element, model, controls, scene=None):
        super(ModelerGraphicItem, self).__init__(None)
        self.controls = controls
        self.model = model
        self.scene = scene
        self.element = element
        if isinstance(element, QgsProcessingModelParameter):
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'input.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            paramDef = self.model.parameterDefinition(element.parameterName())
            if paramDef:
                self.text = paramDef.description()
            else:
                self.text = 'Error ({})'.format(element.parameterName())
        elif isinstance(element, QgsProcessingModelOutput):
            # Output name
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'output.svg'))
            self.picture = QPicture()
            painter = QPainter(self.picture)
            svg.render(painter)
            self.pixmap = None
            self.text = element.name()
        else:
            if element.algorithm().svgIconPath():
                svg = QSvgRenderer(element.algorithm().svgIconPath())
                size = svg.defaultSize()
                self.picture = QPicture()
                painter = QPainter(self.picture)
                painter.scale(16 / size.width(), 16 / size.width())
                svg.render(painter)
                self.pixmap = None
            else:
                self.pixmap = element.algorithm().icon().pixmap(15, 15)
            self.text = element.description()
        self.arrows = []
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setZValue(1000)

        if controls:
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'edit.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 -
                         FlatButtonGraphicItem.WIDTH / 2,
                         ModelerGraphicItem.BOX_HEIGHT / 2 -
                         FlatButtonGraphicItem.HEIGHT / 2)
            self.editButton = FlatButtonGraphicItem(picture, pt, self.editElement)
            self.editButton.setParentItem(self)
            svg = QSvgRenderer(os.path.join(pluginPath, 'images', 'delete.svg'))
            picture = QPicture()
            painter = QPainter(picture)
            svg.render(painter)
            pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 -
                         FlatButtonGraphicItem.WIDTH / 2,
                         FlatButtonGraphicItem.HEIGHT / 2 -
                         ModelerGraphicItem.BOX_HEIGHT / 2)
            self.deleteButton = FlatButtonGraphicItem(picture, pt,
                                                      self.removeElement)
            self.deleteButton.setParentItem(self)

        if isinstance(element, QgsProcessingModelChildAlgorithm):
            alg = element.algorithm()
            if [a for a in alg.parameterDefinitions() if not a.isDestination()]:
                pt = self.getLinkPointForParameter(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.inButton = FoldButtonGraphicItem(pt, self.foldInput, self.element.parametersCollapsed())
                    self.inButton.setParentItem(self)
            if alg.outputDefinitions():
                pt = self.getLinkPointForOutput(-1)
                pt = QPointF(0, pt.y())
                if controls:
                    self.outButton = FoldButtonGraphicItem(pt, self.foldOutput, self.element.outputsCollapsed())
                    self.outButton.setParentItem(self)
Ejemplo n.º 28
0
    def test_tool(self):
        """
        Test some plot tool logic
        """
        canvas = QgsElevationProfileCanvas()
        canvas.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.setProject(QgsProject.instance())
        canvas.show()
        self.assertEqual(canvas.width(), 600)
        self.assertEqual(canvas.height(), 400)
        ls = QgsLineString()
        ls.fromWkt('LineString(0 2, 10 2, 10 4)')
        canvas.setProfileCurve(ls)
        canvas.setVisiblePlotRange(0, ls.length(), 0, 100)

        self.assertFalse(canvas.tool())
        tool = TestTool(canvas)
        self.assertFalse(tool.isActive())
        canvas.setTool(tool)
        self.assertEqual(canvas.tool(), tool)

        key_press_event = QKeyEvent(QEvent.KeyPress, 54, Qt.ShiftModifier)
        canvas.keyPressEvent(key_press_event)
        self.assertEqual(tool.events[-1].type(), QEvent.KeyPress)

        key_release_event = QKeyEvent(QEvent.KeyRelease, 54, Qt.ShiftModifier)
        canvas.keyReleaseEvent(key_release_event)
        self.assertEqual(tool.events[-1].type(), QEvent.KeyRelease)

        mouse_dbl_click_event = QMouseEvent(QEvent.MouseButtonDblClick,
                                            QPointF(300, 200), Qt.LeftButton,
                                            Qt.MouseButtons(),
                                            Qt.ShiftModifier)
        canvas.mouseDoubleClickEvent(mouse_dbl_click_event)
        self.assertEqual(tool.events[-1].type(), QEvent.MouseButtonDblClick)
        self.assertIsInstance(tool.events[-1], QgsPlotMouseEvent)
        self.assertAlmostEqual(tool.events[-1].mapPoint().x(), 5.92, 1)
        self.assertAlmostEqual(tool.events[-1].mapPoint().y(), 2, 4)
        self.assertAlmostEqual(tool.events[-1].mapPoint().z(), 49.165, 0)

        mouse_move_event = QMouseEvent(QEvent.MouseMove,
                                       QPointF(300, 200), Qt.LeftButton,
                                       Qt.MouseButtons(), Qt.ShiftModifier)
        canvas.mouseMoveEvent(mouse_move_event)
        self.assertEqual(tool.events[-1].type(), QEvent.MouseMove)
        self.assertIsInstance(tool.events[-1], QgsPlotMouseEvent)
        self.assertAlmostEqual(tool.events[-1].mapPoint().x(), 5.92, 1)
        self.assertAlmostEqual(tool.events[-1].mapPoint().y(), 2, 4)
        self.assertAlmostEqual(tool.events[-1].mapPoint().z(), 49.165, 0)

        mouse_press_event = QMouseEvent(QEvent.MouseButtonPress,
                                        QPointF(300, 200), Qt.LeftButton,
                                        Qt.MouseButtons(), Qt.ShiftModifier)
        canvas.mousePressEvent(mouse_press_event)
        self.assertEqual(tool.events[-1].type(), QEvent.MouseButtonPress)
        self.assertIsInstance(tool.events[-1], QgsPlotMouseEvent)
        self.assertAlmostEqual(tool.events[-1].mapPoint().x(), 5.927, 1)
        self.assertAlmostEqual(tool.events[-1].mapPoint().y(), 2, 4)
        self.assertAlmostEqual(tool.events[-1].mapPoint().z(), 49.165, 0)

        mouse_release_event = QMouseEvent(QEvent.MouseButtonRelease,
                                          QPointF(300, 200), Qt.LeftButton,
                                          Qt.MouseButtons(), Qt.ShiftModifier)
        canvas.mouseReleaseEvent(mouse_release_event)
        self.assertEqual(tool.events[-1].type(), QEvent.MouseButtonRelease)
        self.assertIsInstance(tool.events[-1], QgsPlotMouseEvent)
        self.assertAlmostEqual(tool.events[-1].mapPoint().x(), 5.927, 1)
        self.assertAlmostEqual(tool.events[-1].mapPoint().y(), 2, 4)
        self.assertAlmostEqual(tool.events[-1].mapPoint().z(), 49.165, 0)

        wheel_event = QWheelEvent(QPointF(300, 200), QPointF(300, 200),
                                  QPoint(1, 2), QPoint(3, 4), Qt.NoButton,
                                  Qt.NoModifier, Qt.ScrollBegin, False)
        canvas.wheelEvent(wheel_event)
        self.assertEqual(tool.events[-1].type(), QEvent.Wheel)