Ejemplo n.º 1
0
 def setRequired(self, required):
     self.required = required
     brush = QBrush()
     if required:
         brush.setColor(QColor(255, 0, 0))
     else:
         brush.setColor(QColor(0, 0, 0))
     self.setForeground(0, brush)
Ejemplo n.º 2
0
 def setRequired(self, required):
     self.required = required
     brush = QBrush()
     if required:
         brush.setColor(QColor(255, 0, 0))
     else:
         brush.setColor(QColor(0, 0, 0))
     self.setForeground(0, brush)
Ejemplo n.º 3
0
def brush_darker(brush, factor):
    """Return a copy of the brush darkened by factor.
    """
    grad = brush.gradient()
    if grad:
        return QBrush(gradient_darker(grad, factor))
    else:
        brush = QBrush(brush)
        brush.setColor(brush.color().darker(factor))
        return brush
Ejemplo n.º 4
0
def brush_darker(brush, factor):
    """Return a copy of the brush darkened by factor.
    """
    grad = brush.gradient()
    if grad:
        return QBrush(gradient_darker(grad, factor))
    else:
        brush = QBrush(brush)
        brush.setColor(brush.color().darker(factor))
        return brush
Ejemplo n.º 5
0
 def drawPoints(self):
     img = qrcode.make('TestCode 001',image_factory=qrcode.image.svg.SvgImage )
     type(img)
     gitem =  QGraphicsScene()
     self.graphicsView.setScene(gitem)
     #gitem.addLine(0, 0, 2, 2)
     qbrush = QBrush()
     qbrush.setStyle(Qt.SolidPattern)
     qbrush.setColor(Qt.black)
     gitem.addRect(0, 0, 2, 2, brush=qbrush )
     self.graphicsView.show()
Ejemplo n.º 6
0
    def _drawMeasurements(self):
        if self.selNuc is None: return

        painter = QPainter()
        painter.begin(self.imagePixmap)
        painter.setRenderHint(QPainter.Antialiasing)

        rng_thick = 3
        rng_thick *= self.pix_per_um

        if self.activeCh == "dna":
            # get nuclei boundary as a polygon
            nucb_qpoints_e = [
                Qt.QPoint(x, y)
                for x, y in self.selNuc.buffer(rng_thick).exterior.coords
            ]
            nucb_qpoints_i = [
                Qt.QPoint(x, y) for x, y in self.selNuc.exterior.coords
            ]

            painter.setPen(QPen(QBrush(QColor('white')), 3))
            painter.drawPolygon(Qt.QPolygon(nucb_qpoints_i))
            painter.drawPolygon(Qt.QPolygon(nucb_qpoints_e))

            nucb_poly = Qt.QPolygon(nucb_qpoints_e).subtracted(
                Qt.QPolygon(nucb_qpoints_i))
            brush = QBrush(QtCore.Qt.BDiagPattern)
            brush.setColor(QColor('white'))
            painter.setBrush(brush)
            painter.setPen(QPen(QBrush(QColor('transparent')), 0))

            painter.drawPolygon(nucb_poly)

        elif self.activeCh == "act":
            nuc_pen = QPen(QBrush(QColor('red')), 2)
            nuc_pen.setStyle(QtCore.Qt.DotLine)
            painter.setPen(nuc_pen)
            for n in [e["boundary"] for e in self._boudaries]:
                # get nuclei boundary as a polygon
                nucb_qpoints = [Qt.QPoint(x, y) for x, y in n.exterior.coords]
                painter.drawPolygon(Qt.QPolygon(nucb_qpoints))

        for me in self.measurements:
            painter.setPen(
                QPen(
                    QBrush(QColor(me['c'])), 2 * self.pix_per_um
                    if me == self.selectedLine else self.pix_per_um))
            pts = [Qt.QPoint(x, y) for x, y in [me['ls0'], me['ls1']]]
            painter.drawLine(pts[0], pts[1])

        painter.end()
Ejemplo n.º 7
0
 def _setup(self):
     self.rod = QGraphicsLineItem(QLineF(0, 0, 0, 100))
     p = QPen(QColor(100, 100, 100))
     p.setWidth(5)
     self.rod.setPen(p)
     self.rod.setToolTip('This is the rod of the pendulum')
     self.ball = QGraphicsEllipseItem(QRectF(-20, 80, 40, 40))
     b = QBrush(Qt.SolidPattern)
     b.setColor(QColor(0, 255, 0))
     self.ball.setBrush(b)
     self.ball.setToolTip('This is the ball of the pendulum where the mass is concentrated')
     self.addToGroup(self.rod)
     self.addToGroup(self.ball)
     self.setFlags(QGraphicsItem.ItemIsSelectable)
Ejemplo n.º 8
0
    def data(self, index, role):
        if not index.isValid():
            return None

        item = index.internalPointer()
        node = item.node()
        attributes = []
        attributeMap = node.attributes()
        
        if role == Qt.DisplayRole:
            if index.column() == 0:
                return attributeMap.namedItem("subject").nodeValue()
            elif index.column() == 1:
                return attributeMap.namedItem(
                                    "percentageComplete").nodeValue().toInt()[0]
            return None
            
        elif role == Qt.CheckStateRole:
            if index.column() == 0:
                if attributeMap.namedItem(
                                    "percentageComplete").nodeValue() == "100": 
                    return Qt.Checked
                else:
                    return Qt.Unchecked
                
        elif role == Qt.FontRole:
            if index.column() == 0:
                font = QFont()
                if attributeMap.namedItem(
                                    "percentageComplete").nodeValue() == "100":
                    font.setStrikeOut(True)
                else:
                    font.setStrikeOut(False)
                return font
            
        elif role == Qt.ForegroundRole:
            if index.column() == 0:            
                if attributeMap.namedItem(
                                    "percentageComplete").nodeValue() == "100":
                    brush = QBrush()
                    brush.setColor(QColor("grey"))
                    return brush
                
        return None
Ejemplo n.º 9
0
    def data(self, index, role=Qt.DisplayRole):
        column = index.column()

        if role == Qt.DisplayRole:
            field = self._mapping[index.row()]
            column_def = self.columns[column]
            value = field[column_def['name']]

            fieldType = column_def['type']
            if fieldType == QVariant.Type:
                if value == QVariant.Invalid:
                    return ''
                return self.fieldTypes[value]
            return value

        if role == Qt.EditRole:
            field = self._mapping[index.row()]
            column_def = self.columns[column]
            value = field[column_def['name']]
            return value

        if role == Qt.TextAlignmentRole:
            fieldType = self.columns[column]['type']
            if fieldType in [QVariant.Int]:
                hAlign = Qt.AlignRight
            else:
                hAlign = Qt.AlignLeft
            return hAlign + Qt.AlignVCenter

        if role == Qt.ForegroundRole:
            column_def = self.columns[column]
            if column_def['name'] == 'expression':
                brush = QBrush()
                if self._errors[index.row()]:
                    brush.setColor(Qt.red)
                else:
                    brush.setColor(Qt.black)
                return brush

        if role == Qt.ToolTipRole:
            column_def = self.columns[column]
            if column_def['name'] == 'expression':
                return self._errors[index.row()]
Ejemplo n.º 10
0
 def __init__(self):
     super(QFramesInTracksScene, self).__init__()
     self._coords = CoordTransform()
     self._track_items = {}
     self._frame_items = {}
     pen = QPen()
     pen.setWidthF(1.25)
     pen.setColor(Qt.black)
     # pen.setCapStyle(Qt.RoundCap)
     pen.setJoinStyle(Qt.RoundJoin)
     brush = QBrush()
     brush.setColor(Qt.blue)
     brush.setStyle(Qt.SolidPattern)
     self._frame_pen_brush = pen, brush
     pen = QPen(pen)
     pen.setWidthF(3.5)
     pen.setJoinStyle(Qt.RoundJoin)
     pen.setColor(Qt.blue)
     brush = QBrush(brush)
     brush.setColor(Qt.gray)
     self._track_pen_brush = pen, brush
Ejemplo n.º 11
0
    def data(self, idx, role=Qt.DisplayRole):
        d = self.data_list[idx.row()]
        if role == Qt.DisplayRole:
            if idx.column() == 1:
                return d.device_type()
            elif idx.column() == 0:
                dname = QString(d.device_name())
                if d.is_hide():
                    dname = QString("%1 (%2)").arg(dname).arg(self.tr("disable notification"))
                return dname
        elif role == Qt.DecorationRole:
            if d.device_type() == "net":
                return self.wifi_icon
            else:
                return self.hard_icon
        elif role == Qt.TextColorRole:
            if len(d.selected_driver()) != 0:
                blue_brush = QBrush()
                blue_brush.setColor(Qt.darkBlue)
                return blue_brush

        return QtCore.QVariant()
Ejemplo n.º 12
0
class ColorPanel(QGraphicsItem):
    """docstring for ColorPanel"""
    _colors = styles.stapleColors
    _pen = Qt.NoPen  # QPen(styles.bluestroke, 2)

    def __init__(self, parent=None):
        super(ColorPanel, self).__init__(parent)
        self.rect = QRectF(0, 0, 20, 20)
        self.setFlag(QGraphicsItem.ItemIgnoresTransformations)
        self.colordialog = QColorDialog()
        self.colordialog.setOption(QColorDialog.DontUseNativeDialog)
        self._colorIndex = 0
        self._color = self._colors[0]
        self._brush = QBrush(self._color)
        self.hide()

    def boundingRect(self):
        return self.rect

    def paint(self, painter, option, widget=None):
        painter.setBrush(self._brush)
        painter.setPen(self._pen)
        painter.drawRect(self.boundingRect())

    def nextColor(self):
        """docstring for nextColor"""
        self._colorIndex += 1
        if self._colorIndex == len(self._colors):
            self._colorIndex = 0
        self._color = self._colors[self._colorIndex]
        self._brush.setColor(self._color)

    def colorName(self):
        """docstring for color"""
        return self._color.name()

    def mousePressEvent(self, event):
        self._color = self.colordialog.getColor(self._color)
        self._brush = QBrush(self._color)
Ejemplo n.º 13
0
    def paint(self, painter, option, widget=None):
        painter.save()
        path = self.path()
        brush = QBrush(self.brush())
        pen = QPen(self.pen())

        if option.state & QStyle.State_Selected:
            pen.setColor(Qt.red)
            brush.setStyle(Qt.DiagCrossPattern)
            brush.setColor(QColor(40, 40, 40, 100))

        elif option.state & QStyle.State_MouseOver:
            pen.setColor(Qt.blue)

        if option.state & QStyle.State_MouseOver:
            brush.setColor(QColor(100, 100, 100, 100))
            if brush.style() == Qt.NoBrush:
                # Make sure the highlight is actually visible.
                brush.setStyle(Qt.SolidPattern)

        painter.setPen(pen)
        painter.setBrush(brush)
        painter.drawPath(path)
        painter.restore()
Ejemplo n.º 14
0
    def paint(self, painter, option, widget=None):
        painter.save()
        path = self.path()
        brush = QBrush(self.brush())
        pen = QPen(self.pen())

        if option.state & QStyle.State_Selected:
            pen.setColor(Qt.red)
            brush.setStyle(Qt.DiagCrossPattern)
            brush.setColor(QColor(40, 40, 40, 100))

        elif option.state & QStyle.State_MouseOver:
            pen.setColor(Qt.blue)

        if option.state & QStyle.State_MouseOver:
            brush.setColor(QColor(100, 100, 100, 100))
            if brush.style() == Qt.NoBrush:
                # Make sure the highlight is actually visible.
                brush.setStyle(Qt.SolidPattern)

        painter.setPen(pen)
        painter.setBrush(brush)
        painter.drawPath(path)
        painter.restore()
Ejemplo n.º 15
0
class GeometryHighlightItem(QgsMapCanvasItem):
    # Code ported from QGIS QgsHighlight

    def __init__(self, mapCanvas, geometry, layer):
        super(GeometryHighlightItem, self).__init__(mapCanvas)

        self._mapCanvas = None  # QgsMapCanvas
        self._geometry = None  # QgsGeometry()
        self._brush = QBrush()
        self._pen = QPen()

        self._mapCanvas = mapCanvas
        if not geometry or not isinstance(geometry,
                                          QgsGeometry) or geometry.isEmpty(
                                          ) or not geometry.isGeosValid():
            return
        self._geometry = QgsGeometry(geometry)  # Force deep copy
        self.setLineColor(Application.highlightLineColor())
        self.setFillColor(Application.highlightFillColor())
        if (layer and self._mapCanvas.mapSettings().hasCrsTransformEnabled()):
            ct = self._mapCanvas.mapSettings().layerTransform(layer)
            if ct:
                self._geometry.transform(ct)
        self.updateRect()
        self.update()

    def remove(self):
        self._mapCanvas.scene().removeItem(self)

    def setLineWidth(self, width):
        self._pen.setWidth(width)

    def setLineColor(self, color):
        lineColor = QColor(color)
        lineColor.setAlpha(255)
        self._pen.setColor(lineColor)

    def setFillColor(self, fillColor):
        self._brush.setColor(fillColor)
        self._brush.setStyle(Qt.SolidPattern)

    def updatePosition(self):
        pass

    # protected:
    def paint(self, painter, option=None, widget=None):  # Override
        if not self._geometry:
            return

        painter.setPen(self._pen)
        painter.setBrush(self._brush)

        wkbType = self._geometry.wkbType()
        if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:
            self._paintPoint(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiPoint or wkbType == QGis.WKBMultiPoint25D:
            for point in self._geometry.geometry():
                self._paintPoint(painter, point)
        elif wkbType == QGis.WKBLineString or wkbType == QGis.WKBLineString25D:
            self._paintLine(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiLineString or wkbType == QGis.WKBMultiLineString25D:
            for line in self._geometry.geometry():
                self._paintLine(painter, line)
        elif wkbType == QGis.WKBPolygon or wkbType == QGis.WKBPolygon25D:
            self._paintPolygon(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiPolygon or wkbType == QGis.WKBMultiPolygon25D:
            for polygon in self._geometry.geometry():
                self._paintPolygon(painter, polygon)

    def updateRect(self):
        if self._geometry:
            r = self._geometry.boundingBox()
            if r.isEmpty():
                d = self._mapCanvas.extent().width() * 0.005
                r.setXMinimum(r.xMinimum() - d)
                r.setYMinimum(r.yMinimum() - d)
                r.setXMaximum(r.xMaximum() + d)
                r.setYMaximum(r.yMaximum() + d)
            self.setRect(r)
            self.setVisible(True)
        else:
            self.setRect(QgsRectangle())

    # private:

    def _paintPoint(self, painter, point):
        painter.drawEllipse(self.toCanvasCoordinates(point) - self.pos(), 2, 2)

    def _paintLine(self, painter, line):
        polyline = QPolygonF()
        for point in line:
            polyline.append(self.toCanvasCoordinates(point) - self.pos())
        painter.drawPolyline(polyline)

    def _paintPolygon(self, painter, polygon):
        path = QPainterPath()
        for line in polygon:
            ring = QPolygonF()
            for point in line:
                cur = self.toCanvasCoordinates(point) - self.pos()
                ring.append(cur)
            ring.append(ring[0])
            path.addPolygon(ring)
        painter.drawPath(path)
Ejemplo n.º 16
0
class FeatureHighlightItem(QgsMapCanvasItem):
    # Code ported from QGIS QgsHighlight

    def __init__(self, mapCanvas, feature, layer):
        super(FeatureHighlightItem, self).__init__(mapCanvas)

        self._mapCanvas = None  # QgsMapCanvas
        self._brush = QBrush()
        self._pen = QPen()
        self._feature = None  # QgsFeature()
        self._layer = None  # QgsMapLayer()
        self._buffer = 0.0
        self._minWidth = 0.0

        self._mapCanvas = mapCanvas
        if (not layer or not feature or not isinstance(feature, QgsFeature)
                or not feature.geometry() or feature.geometry().isEmpty()
                or not feature.geometry().isGeosValid()):
            return
        self._feature = QgsFeature(feature)  # Force deep copy
        self._layer = layer
        self.setLineColor(Application.highlightLineColor())
        self.setFillColor(Application.highlightFillColor())
        self._minWidth = Application.highlightMinimumWidth()
        self._buffer = Application.highlightBuffer()
        if self._mapCanvas.mapSettings().hasCrsTransformEnabled():
            ct = self._mapCanvas.mapSettings().layerTransform(self._layer)
            if ct:
                self._feature.geometry().transform(ct)
        self.updateRect()
        self.update()

    def remove(self):
        self._mapCanvas.scene().removeItem(self)

    def setLineWidth(self, width):
        self._pen.setWidth(width)

    def setLineColor(self, color):
        self._pen.setColor(color)

    def setFillColor(self, fillColor):
        self._brush.setColor(fillColor)
        self._brush.setStyle(Qt.SolidPattern)

    def setBuffer(self, buff):
        self._buffer = buff

    def setMinWidth(self, width):
        self._minWidth = width

    def layer(self):
        return self._layer

    def updatePosition(self):
        pass

    # protected:
    def paint(self, painter, option=None, widget=None):  # Override
        if not self._feature:
            return

        mapSettings = self._mapCanvas.mapSettings()
        context = QgsRenderContext.fromMapSettings(mapSettings)
        renderer = self._getRenderer(context, self._pen.color(),
                                     self._brush.color())

        if renderer:
            context.setPainter(painter)
            renderer.startRender(context, self._layer.fields())
            renderer.renderFeature(self._feature, context)
            renderer.stopRender(context)

    def updateRect(self):
        if self._feature and self._feature.constGeometry():
            m2p = self._mapCanvas.mapSettings().mapToPixel()
            topLeft = m2p.toMapPoint(0, 0)
            res = m2p.mapUnitsPerPixel()
            imageSize = self._mapCanvas.mapSettings().outputSize()
            rect = QgsRectangle(topLeft.x(), topLeft.y(),
                                topLeft.x() + imageSize.width() * res,
                                topLeft.y() - imageSize.height() * res)
            self.setRect(rect)
            self.setVisible(True)
        else:
            self.setRect(QgsRectangle())

    # private:
    def _setSymbol(self, symbol, context, color, fillColor):
        if not symbol:
            return

        for symbolLayer in reversed(symbol.symbolLayers()):
            if symbolLayer:
                if symbolLayer.subSymbol():
                    self._setSymbol(symbolLayer.subSymbol(), context, color,
                                    fillColor)
                else:
                    symbolLayer.setColor(color)
                    symbolLayer.setOutlineColor(color)
                    symbolLayer.setFillColor(fillColor)
                    if isinstance(symbolLayer, QgsSimpleMarkerSymbolLayerV2):
                        symbolLayer.setOutlineWidth(
                            self._getSymbolWidth(
                                context, symbolLayer.outlineWidth(),
                                symbolLayer.outlineWidthUnit()))
                    if symbolLayer.type() == QgsSymbolV2.Line:
                        symbolLayer.setWidth(
                            self._getSymbolWidth(context, symbolLayer.width(),
                                                 symbolLayer.widthUnit()))
                    if symbolLayer.type() == QgsSymbolV2.Fill:
                        symbolLayer.setBorderWidth(
                            self._getSymbolWidth(context,
                                                 symbolLayer.borderWidth(),
                                                 symbolLayer.outputUnit()))
                    symbolLayer.removeDataDefinedProperty('color')
                    symbolLayer.removeDataDefinedProperty('color_border')

    def _getSymbolWidth(self, context, width, unit):
        scale = 1.0
        if unit == QgsSymbolV2.MapUnit:
            scale = QgsSymbolLayerV2Utils.lineWidthScaleFactor(
                context,
                QgsSymbolV2.MM) / QgsSymbolLayerV2Utils.lineWidthScaleFactor(
                    context, QgsSymbolV2.MapUnit)
        width = max(width + 2 * self._buffer * scale, self._minWidth * scale)
        return width

    def _getRenderer(self, context, color, fillColor):
        renderer = None
        if self._layer and self._layer.rendererV2():
            renderer = self._layer.rendererV2().clone()
        if renderer:
            for symbol in renderer.symbols2(context):
                self._setSymbol(symbol, context, color, fillColor)
        return renderer
Ejemplo n.º 17
0
    def drawForeground(self, painter, rect):
        #print "BoreHoleScene.drawForeground"
        if self.__redraw:
            with self.__project.connect() as con:
                cur = con.cursor()
                self.__redraw = False
                self.clear()
                fm = painter.fontMetrics()

                if self.__id is None:
                    QGraphicsScene.drawForeground(self, painter, rect)
                    return

                cur.execute(
                    "SELECT geom FROM albion.hole WHERE id='{}'".format(
                        self.__id))
                res = cur.fetchone()

                if not res:
                    QGraphicsScene.drawForeground(self, painter, rect)
                    return

                hole = wkb.loads(bytes.fromhex(res[0]))
                line = [p[2] for p in hole.coords]
                tick_width = 20
                spacing = 5
                tick_text_offset = -10
                tabs = [50, 75, 150, 250, 350, 400, 500]
                zmin, zmax = min(line), max(line)
                zpmin, zpmax = 0, ((zmin - zmax) - 5) / self.m_per_pixel

                text = self.addText(self.__id)
                text.setPos(tabs[1], -5 * fm.height())

                label = 'Depth [m]'
                text = self.addText(label)
                text.setRotation(-90)
                text.setPos(0, 0)
                text = self.addText('Formation')
                text.setPos(tabs[1], -3 * fm.height())
                text = self.addText('Radiometry')
                text.setPos(tabs[2], -3 * fm.height())
                text = self.addText('Resistivity')
                text.setPos(tabs[3], -3 * fm.height())
                text = self.addText('Mineralization')
                text.setPos(tabs[4], -3 * fm.height())

                top = zpmin - 3 * fm.height()
                pen = QPen()
                pen.setWidth(3)
                for tab in [tabs[1], tabs[2], tabs[3], tabs[4], tabs[6]]:
                    self.addLine(tab, top, tab, zpmax, pen)
                self.addLine(tabs[1], zpmin, tabs[-1], zpmin, pen)
                self.addLine(tabs[1], zpmax, tabs[-1], zpmax, pen)
                self.addLine(tabs[1], top, tabs[-1], top, pen)

                # depth ticks
                for z in range(0, int(-(zmax - zmin) - 5), -10):
                    text = "% 4.0f" % (max(line) + z)
                    z /= self.m_per_pixel
                    width = fm.width(text)
                    text = self.addText(text)
                    text.setPos(tabs[0] - width - spacing,
                                tick_text_offset + int(z))
                    self.addLine(tabs[0], z, tabs[1], z)
                    self.addLine(tabs[2], z, tabs[4], z)

                #res = cur.execute("SELECT AsText(GEOMETRY), code FROM lithologies WHERE forage={}".format(self.__id)).fetchall()

                ## litho image
                #for geom, code in res:
                #    line = [(float(pt.split()[2])-z_tube+h_tube_sol)
                #            for pt in geom.replace('LINESTRING Z(','').replace(')','').split(',')]
                #    z_start = line[0]/self.m_per_pixel
                #    z_end = line[-1]/self.m_per_pixel
                #    brush = QBrush()
                #    brush.setTextureImage(self.texture(code))
                #    self.addRect(tabs[1], z_start, tabs[2]-tabs[1], z_end-z_start, brush=brush)

                ## bar diagram grid
                #for i in range(1, 10):
                #    pen.setWidth(1 if i != 5 else 2)
                #    x = tabs[3]+(tabs[4]-tabs[3])*float(i)/10
                #    self.addLine(x, zmin, x, zmax, pen)

                # formation color
                cur.execute(
                    "SELECT geom, code FROM albion.formation WHERE hole_id='{}'"
                    .format(self.__id))

                for geom, code in cur.fetchall():
                    line = [
                        p[2] for p in wkb.loads(bytes.fromhex(geom)).coords
                    ]
                    z_start = (line[0] - zmax) / self.m_per_pixel
                    z_end = (line[-1] - zmax) / self.m_per_pixel
                    brush = QBrush()
                    brush.setStyle(Qt.SolidPattern)
                    brush.setColor(self.formation_color(code))
                    self.addRect(tabs[1],
                                 z_start,
                                 tabs[2] - tabs[1],
                                 z_end - z_start,
                                 brush=brush)
                    #width = fm.width(code);
                    #text = self.addText(code)
                    #text.setPos(tabs[2]+spacing, tick_text_offset+int(.5*(z_start+z_end)))
                    self.addLine(tabs[2], z_start, tabs[2], z_start)
                    self.addLine(tabs[2], z_end, tabs[2], z_end)

                # radiometry diagram
                cur.execute(
                    "SELECT max(gamma) FROM albion.radiometry WHERE hole_id='{}'"
                    .format(self.__id))
                gamma_max = cur.fetchone()[0]
                cur.execute(
                    "SELECT geom, gamma FROM albion.radiometry WHERE hole_id='{}' AND gamma>=0"
                    .format(self.__id))
                for geom, gamma in cur.fetchall():
                    line = [
                        p[2] for p in wkb.loads(bytes.fromhex(geom)).coords
                    ]
                    z_start = (line[0] - zmax) / self.m_per_pixel
                    z_end = (line[-1] - zmax) / self.m_per_pixel
                    brush = QBrush()
                    brush.setStyle(Qt.SolidPattern)
                    brush.setColor(QColor(55, 51, 149))
                    self.addRect(tabs[2],
                                 z_start,
                                 (tabs[3] - tabs[2]) * gamma / gamma_max,
                                 z_end - z_start,
                                 pen=QPen(Qt.NoPen),
                                 brush=brush)

                # resistivity diagram
                cur.execute(
                    "SELECT max(rho) FROM albion.resistivity WHERE hole_id='{}'"
                    .format(self.__id))
                rho_max = cur.fetchone()[0]
                cur.execute(
                    "SELECT geom, rho FROM albion.resistivity WHERE hole_id='{}' AND rho>=0"
                    .format(self.__id))
                for geom, rho in cur.fetchall():
                    line = [
                        p[2] for p in wkb.loads(bytes.fromhex(geom)).coords
                    ]
                    z_start = (line[0] - zmax) / self.m_per_pixel
                    z_end = (line[-1] - zmax) / self.m_per_pixel
                    brush = QBrush()
                    brush.setStyle(Qt.SolidPattern)
                    brush.setColor(QColor(155, 51, 49))
                    self.addRect(tabs[3],
                                 z_start, (tabs[4] - tabs[3]) * rho / rho_max,
                                 z_end - z_start,
                                 pen=QPen(Qt.NoPen),
                                 brush=brush)

                # mineralization
                cur.execute(
                    "SELECT geom, oc, accu, grade FROM albion.mineralization WHERE hole_id='{}'"
                    .format(self.__id))

                for geom, oc, accu, grade in cur.fetchall():
                    line = [
                        p[2] for p in wkb.loads(bytes.fromhex(geom)).coords
                    ]
                    z_start = (line[0] - zmax) / self.m_per_pixel
                    z_end = (line[-1] - zmax) / self.m_per_pixel
                    brush = QBrush()
                    brush.setStyle(Qt.SolidPattern)
                    brush.setColor(QColor(250, 250, 50))
                    self.addRect(tabs[4],
                                 z_start,
                                 tabs[5] - tabs[4],
                                 z_end - z_start,
                                 brush=brush)
                    txt = "oc=" + str(oc) + "\naccu=" + str(
                        accu) + "\ngrade=" + str(grade)
                    width = fm.width(txt)
                    text = self.addText(txt)
                    text.setPos(
                        tabs[5] + spacing,
                        -int(1.5 * fm.height()) + int(.5 * (z_start + z_end)))
                    self.addLine(tabs[4], z_start, tabs[6], z_start)
                    self.addLine(tabs[4], z_end, tabs[6], z_end)

                self.setSceneRect(self.itemsBoundingRect())

        QGraphicsScene.drawForeground(self, painter, rect)
Ejemplo n.º 18
0
	def populateTree(self):
		"""Populates tree view with information from ItemTracker."""
		if len(self.errorIds):
			self.mkError("{0} entries do not have valid "
			"ItemTracker IDs in Bionumerics.".format(len(self.errorIds)))

			for key, msg in self.errorIds.iteritems():
				self.mkError("KEY: {0} {1}".format(key, msg))

		if not len(self.selectedIds):
			self.statusbar.showMessage("No items to process", 5000)
			return

		parents = {}
		headers = ["Items", "Selected", "SelectedBy", "Viability", "Volume",
				 "DNA concentration", "UserName", "TubePresent", "InputDate",
				 "AlternID", "Status"]

		self.treeWidget.setItemsExpandable(True)
		self.treeWidget.setAlternatingRowColors(True)
		self.treeWidget.setColumnCount(len(headers))
		self.treeWidget.setHeaderLabels(headers)

		msg = "Getting information from ItemTracker. Please wait..."
		self.statusbar.showMessage(msg)

		self.progressBar.setMinimum(0)
		self.progressBar.setMaximum(0)
		self.progressBar.show()

		(treeData, self.itemProperties,
		 message) = lims.GetDictionary((self.selectedIds.keys()))

		if len(message):
			for msg in message:
				self.mkError("ItemTracker error: {0}".format(msg))

		if not len(treeData):
			self.mkError("Could not get data from ItemTracker for"
						"selected entries")
			self.statusBar().clearMessage()
			self.progressBar.hide()
			self.updateUi()
			return

		# bugfix: If ItemType property does not exist for the first item
		# self.database is not set and tree view is not updated.
		db = None
		if not self.database:
			for item in self.itemProperties.values():
				try:
					db = item["ItemType"]
				except KeyError:
					pass

				if db == "Salmonella":
					self.database = db
					break
				elif db == "Listeria":
					self.database = db
					break

		self.progressBar.setMaximum(len(treeData))
		count = 0
		for key, value  in treeData.iteritems():
			count += 1
			self.progressBar.setValue(count)
			if not(value and isinstance(value, dict)):
				self.mkWarn("No data returned for key {0}".format(key))
				continue

			items = {}
			items[key] = value
			for results in self.getData(items, key):
				parent = parents.get(results[0])

				if not parent:
					parent_id = self.selectedIds[results[0]]
					self.strainInfo[parent_id] = {self.database:[],
												"Frozen Stock":[], "DNA":[]}
					parent = QTreeWidgetItem(self.treeWidget,
					[unicode(parent_id)])

					brush = QBrush()
					brush.setColor(Qt.blue)
					parent.setForeground(0, brush)
					parent.setIcon(0, QIcon(":/branch-closed.png"))
					parent.setData(0, Qt.CheckStateRole, QVariant())
					parents[results[0]] = parent

				for children in results[1]:
					itemName = self.itemProperties[children]["ItemName"]
					if not self.itemIds.get(itemName):
						self.itemIds[itemName] = children

					childprops = []
					childprops.append(unicode(itemName))

					for header in headers[1:]:
						try:
							childprop = self.itemProperties[children][header]

							if childprop is None or childprop == "":
								childprops.append(unicode(""))
							else:
								childprops.append(unicode(childprop))
						except KeyError:
							childprops.append(unicode(""))
							continue

					childs = parents.get(children)
					if not childs:
						childs = QTreeWidgetItem(parent, childprops)

						if self.itemProperties[children]["TubePresent"] == "-":
							childs.setBackgroundColor(0, QColor(232, 87, 82))
							childs.setForeground(0, QColor(255, 255, 255))

						if self.itemProperties[children]["Selected"] == "yes":
							childs.setBackgroundColor(0, QColor(119, 183, 83))
							childs.setForeground(0, QColor(255, 255, 255))

						itype = self.itemProperties[children]["ItemType"]
						if itype:
							self.strainInfo[parent_id][itype].append(itemName)
						parents[children] = childs
					childs.setCheckState(0, Qt.Unchecked)

		self.treeWidget.expandAll()
		for i in range(len(headers)):
			self.treeWidget.resizeColumnToContents(i)
		if not self.treeWidget.isEnabled():
			self.treeWidget.setEnabled(True)
		self.mkInfo("Processed <b>{0}</b> entries".format(len(treeData)))

		self.progressBar.setValue(len(treeData))
		self.progressBar.hide()
		self.populatedTree = True
		self.updateUi()
		self.statusbar.showMessage("Ready", 5000)
class GeometryHighlightItem(QgsMapCanvasItem):
    # Code ported from QGIS QgsHighlight

    def __init__(self, mapCanvas, geometry, layer):
        super(GeometryHighlightItem, self).__init__(mapCanvas)

        self._mapCanvas = None  # QgsMapCanvas
        self._geometry = None  # QgsGeometry()
        self._brush = QBrush()
        self._pen = QPen()

        self._mapCanvas = mapCanvas
        if not geometry or not isinstance(geometry, QgsGeometry) or geometry.isEmpty() or not geometry.isGeosValid():
            return
        self._geometry = QgsGeometry(geometry)  # Force deep copy
        self.setLineColor(Application.highlightLineColor())
        self.setFillColor(Application.highlightFillColor())
        if (layer and self._mapCanvas.mapSettings().hasCrsTransformEnabled()):
            ct = self._mapCanvas.mapSettings().layerTransform(layer)
            if ct:
                self._geometry.transform(ct)
        self.updateRect()
        self.update()

    def remove(self):
        self._mapCanvas.scene().removeItem(self)

    def setLineWidth(self, width):
        self._pen.setWidth(width)

    def setLineColor(self, color):
        lineColor = QColor(color)
        lineColor.setAlpha(255)
        self._pen.setColor(lineColor)

    def setFillColor(self, fillColor):
        self._brush.setColor(fillColor)
        self._brush.setStyle(Qt.SolidPattern)

    def updatePosition(self):
        pass

    # protected:
    def paint(self, painter, option=None, widget=None):  # Override
        if not self._geometry:
            return

        painter.setPen(self._pen)
        painter.setBrush(self._brush)

        wkbType = self._geometry.wkbType()
        if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:
            self._paintPoint(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiPoint or wkbType == QGis.WKBMultiPoint25D:
            for point in self._geometry.geometry():
                self._paintPoint(painter, point)
        elif wkbType == QGis.WKBLineString or wkbType == QGis.WKBLineString25D:
            self._paintLine(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiLineString or wkbType == QGis.WKBMultiLineString25D:
            for line in self._geometry.geometry():
                self._paintLine(painter, line)
        elif wkbType == QGis.WKBPolygon or wkbType == QGis.WKBPolygon25D:
            self._paintPolygon(painter, self._geometry.geometry())
        elif wkbType == QGis.WKBMultiPolygon or wkbType == QGis.WKBMultiPolygon25D:
            for polygon in self._geometry.geometry():
                self._paintPolygon(painter, polygon)

    def updateRect(self):
        if self._geometry:
            r = self._geometry.boundingBox()
            if r.isEmpty():
                d = self._mapCanvas.extent().width() * 0.005
                r.setXMinimum(r.xMinimum() - d)
                r.setYMinimum(r.yMinimum() - d)
                r.setXMaximum(r.xMaximum() + d)
                r.setYMaximum(r.yMaximum() + d)
            self.setRect(r)
            self.setVisible(True)
        else:
            self.setRect(QgsRectangle())

    # private:

    def _paintPoint(self, painter, point):
        painter.drawEllipse(self.toCanvasCoordinates(point) - self.pos(), 2, 2)

    def _paintLine(self, painter, line):
        polyline = QPolygonF()
        for point in line:
            polyline.append(self.toCanvasCoordinates(point) - self.pos())
        painter.drawPolyline(polyline)

    def _paintPolygon(self, painter, polygon):
        path = QPainterPath()
        for line in polygon:
            ring = QPolygonF()
            for point in line:
                cur = self.toCanvasCoordinates(point) - self.pos()
                ring.append(cur)
            ring.append(ring[0])
            path.addPolygon(ring)
        painter.drawPath(path)
Ejemplo n.º 20
0
class FeatureHighlightItem(QgsMapCanvasItem):
    # Code ported from QGIS QgsHighlight

    def __init__(self, mapCanvas, feature, layer):
        super(FeatureHighlightItem, self).__init__(mapCanvas)

        self._mapCanvas = None  # QgsMapCanvas
        self._brush = QBrush()
        self._pen = QPen()
        self._feature = None  # QgsFeature()
        self._layer = None  # QgsMapLayer()
        self._buffer = 0.0
        self._minWidth = 0.0

        self._mapCanvas = mapCanvas
        if (not layer
                or not feature
                or not isinstance(feature, QgsFeature)
                or not feature.geometry()
                or feature.geometry().isEmpty()
                or not feature.geometry().isGeosValid()):
            return
        self._feature = QgsFeature(feature)  # Force deep copy
        self._layer = layer
        self.setLineColor(Application.highlightLineColor())
        self.setFillColor(Application.highlightFillColor())
        self._minWidth = Application.highlightMinimumWidth()
        self._buffer = Application.highlightBuffer()
        if self._mapCanvas.mapSettings().hasCrsTransformEnabled():
            ct = self._mapCanvas.mapSettings().layerTransform(self._layer)
            if ct:
                self._feature.geometry().transform(ct)
        self.updateRect()
        self.update()

    def remove(self):
        self._mapCanvas.scene().removeItem(self)

    def setLineWidth(self, width):
        self._pen.setWidth(width)

    def setLineColor(self, color):
        self._pen.setColor(color)

    def setFillColor(self, fillColor):
        self._brush.setColor(fillColor)
        self._brush.setStyle(Qt.SolidPattern)

    def setBuffer(self, buff):
        self._buffer = buff

    def setMinWidth(self, width):
        self._minWidth = width

    def layer(self):
        return self._layer

    def updatePosition(self):
        pass

    # protected:
    def paint(self, painter, option=None, widget=None):  # Override
        if not self._feature:
            return

        mapSettings = self._mapCanvas.mapSettings()
        context = QgsRenderContext.fromMapSettings(mapSettings)
        renderer = self._getRenderer(context, self._pen.color(), self._brush.color())

        if renderer:
            context.setPainter(painter)
            renderer.startRender(context, self._layer.fields())
            renderer.renderFeature(self._feature, context)
            renderer.stopRender(context)

    def updateRect(self):
        if self._feature and self._feature.constGeometry():
            m2p = self._mapCanvas.mapSettings().mapToPixel()
            topLeft = m2p.toMapPoint(0, 0)
            res = m2p.mapUnitsPerPixel()
            imageSize = self._mapCanvas.mapSettings().outputSize()
            rect = QgsRectangle(topLeft.x(), topLeft.y(), topLeft.x() + imageSize.width()
                                * res, topLeft.y() - imageSize.height() * res)
            self.setRect(rect)
            self.setVisible(True)
        else:
            self.setRect(QgsRectangle())

    # private:
    def _setSymbol(self, symbol, context, color, fillColor):
        if not symbol:
            return

        for symbolLayer in reversed(symbol.symbolLayers()):
            if symbolLayer:
                if symbolLayer.subSymbol():
                    self._setSymbol(symbolLayer.subSymbol(), context, color, fillColor)
                else:
                    symbolLayer.setColor(color)
                    symbolLayer.setOutlineColor(color)
                    symbolLayer.setFillColor(fillColor)
                    if isinstance(symbolLayer, QgsSimpleMarkerSymbolLayerV2):
                        symbolLayer.setOutlineWidth(
                            self._getSymbolWidth(context, symbolLayer.outlineWidth(), symbolLayer.outlineWidthUnit()))
                    if symbolLayer.type() == QgsSymbolV2.Line:
                        symbolLayer.setWidth(
                            self._getSymbolWidth(context, symbolLayer.width(), symbolLayer.widthUnit()))
                    if symbolLayer.type() == QgsSymbolV2.Fill:
                        symbolLayer.setBorderWidth(
                            self._getSymbolWidth(context, symbolLayer.borderWidth(), symbolLayer.outputUnit()))
                    symbolLayer.removeDataDefinedProperty('color')
                    symbolLayer.removeDataDefinedProperty('color_border')

    def _getSymbolWidth(self, context, width, unit):
        scale = 1.0
        if unit == QgsSymbolV2.MapUnit:
            scale = QgsSymbolLayerV2Utils.lineWidthScaleFactor(
                context, QgsSymbolV2.MM) / QgsSymbolLayerV2Utils.lineWidthScaleFactor(context, QgsSymbolV2.MapUnit)
        width = max(width + 2 * self._buffer * scale, self._minWidth * scale)
        return width

    def _getRenderer(self, context, color, fillColor):
        renderer = None
        if self._layer and self._layer.rendererV2():
            renderer = self._layer.rendererV2().clone()
        if renderer:
            for symbol in renderer.symbols2(context):
                self._setSymbol(symbol, context, color, fillColor)
        return renderer
Ejemplo n.º 21
0
class Dial(QGraphicsItem):
    """
    Dial
    """
    
    def __init__(self):
        super(Dial, self).__init__()
        
        self.angle = 0

        # Colors
        self.color               = QColor(120, 120, 120, 255)
        self.notchColor          = QColor(115, 115, 115, 255)
        self.normalBorderColor   = QColor(  255,  255,  255, 30  )
        self.selectedBorderColor = QColor( 255, 191,   0, 102 )
        self.textColor           = QColor(  30,  30,  30, 255 )
        self.shadowColor         = QColor(0, 0, 0, 75)
        self.selectedShadowColor = QColor( 100, 100, 100, 255 )

        # Settings
        self.width, self.height = 75, 75
        
        # Drop Shadow
        self.shadowBlurRadius = 8
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(self.shadowBlurRadius)
        self.shadow.setOffset(0, 0.5)
        self.shadow.setColor(self.shadowColor)
        self.setGraphicsEffect(self.shadow)
        
        # Painter Definitions
        self.pen = QPen()
        gradient = QRadialGradient(self.boundingRect().center() + QPointF(0, -20), 80)
        gradient.setColorAt(0, self.color.lighter(117))
        gradient.setColorAt(1, self.color)
        self.brush = QBrush(gradient)
        self.font  = QFont()
        self.pen.setWidth(1)
        self.pen.setColor(self.normalBorderColor)
        self.brush.setColor(self.color)
        self.font.setPointSize(10)
        
        # Nodegraph Definitions
        self.dragPoint  = None
        self.dragAngle  = 0
        self.dragFactor = 0

        # Notch Specifications
        self.notch = DialNotch()
        self.notch.setParentItem(self)
        self.updateNotch()

    def boundingRect(self):
        """
        Overrides QGraphicsItem's boundingRect() virtual public function and 
        returns a valid bounding rect based on calculated width and height.
        """
        return QRectF(0, 0, self.width, self.height).adjusted(
            -self.shadowBlurRadius, -self.shadowBlurRadius, 
             self.shadowBlurRadius,  self.shadowBlurRadius)

    def paint(self, painter, option, widget):
        """
        Overrides QGraphicsItem's paint() virtual public function.
        """
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        painter.drawEllipse(self.boundingRect())

    def mousePressEvent(self, event):
        self.dragPoint  = event.scenePos()
        self.dragAngle  = self.angle
        part     = self.height / 2
        distance = event.pos().y() - part
        if distance == 0:
            self.dragFactor = 0
        else:
            self.dragFactor = part / distance

    def mouseMoveEvent(self, event):
        scenePos = event.scenePos()
        d = scenePos - self.dragPoint
        self.angle = self.dragAngle + d.x() * self.dragFactor
        self.updateNotch()

    def mouseReleaseEvent(self, event):
        self.dragPoint = None
        self.dragAngle = 0

    def updateNotch(self):
        f  = 0.02
        dx = (self.width  - self.notch.width)  / 2
        dy = (self.height - self.notch.height) / 2
        x  = math.sin(math.radians(self.angle)) * dx + dx
        y  = math.cos(math.radians(self.angle)) * dy + dy
        self.notch.setPos(x, y)