def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.Box | QFrame.Raised) self.setLineWidth(2) self.setMidLineWidth(3) p = QPalette() p.setColor(self.backgroundRole(), QColor(30, 30, 50)) self.setPalette(p) # make curves and maps self.tuples = [] # curve 1 curve = QwtPlotCurve() curve.setPen(QPen(QColor(150, 150, 200), 2)) curve.setStyle(QwtPlotCurve.Lines) curve.setSymbol(QwtSymbol(QwtSymbol.XCross, QBrush(), QPen(Qt.yellow, 2), QSize(7, 7))) self.tuples.append((curve, QwtScaleMap(0, 100, -1.5, 1.5), QwtScaleMap(0, 100, 0.0, 2*np.pi))) # curve 2 curve = QwtPlotCurve() curve.setPen(QPen(QColor(200, 150, 50), 1, Qt.DashDotDotLine)) curve.setStyle(QwtPlotCurve.Sticks) curve.setSymbol(QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.blue), QPen(Qt.yellow), QSize(5, 5))) self.tuples.append((curve, QwtScaleMap(0, 100, 0.0, 2*np.pi), QwtScaleMap(0, 100, -3.0, 1.1))) # curve 3 curve = QwtPlotCurve() curve.setPen(QPen(QColor(100, 200, 150))) curve.setStyle(QwtPlotCurve.Lines) self.tuples.append((curve, QwtScaleMap(0, 100, -1.1, 3.0), QwtScaleMap(0, 100, -1.1, 3.0))) # curve 4 curve = QwtPlotCurve() curve.setPen(QPen(Qt.red)) curve.setStyle(QwtPlotCurve.Lines) self.tuples.append((curve, QwtScaleMap(0, 100, -5.0, 1.1), QwtScaleMap(0, 100, -1.1, 5.0))) # data self.phase = 0.0 self.base = np.arange(0.0, 2.01*np.pi, 2*np.pi/(USize-1)) self.uval = np.cos(self.base) self.vval = np.sin(self.base) self.uval[1::2] *= 0.5 self.vval[1::2] *= 0.5 self.newValues() # start timer self.tid = self.startTimer(250)
def drawColorBar(self, painter, colorMap, interval, scaleMap, orientation, rect): colorTable = [] if colorMap.format() == QwtColorMap.Indexed: colorTable = colorMap.colorTable(interval) c = QColor() devRect = rect.toAlignedRect() pixmap = QPixmap(devRect.size()) pixmap.fill(Qt.transparent) pmPainter = QPainter(pixmap) pmPainter.translate(-devRect.x(), -devRect.y()) if orientation == Qt.Horizontal: sMap = scaleMap sMap.setPaintInterval(rect.left(), rect.right()) for x in range(devRect.left(), devRect.right()+1): value = sMap.invTransform(x) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(x, devRect.top(), devRect.bottom()) else: sMap = scaleMap sMap.setPaintInterval(rect.bottom(), rect.top()) for y in range(devRect.top(), devRect.bottom()+1): value = sMap.invTransform(y) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(devRect.left(), y, devRect.right(), y) pmPainter.end() self.drawPixmap(painter, rect, pixmap)
def drawColorBar(self, painter, rect): h1, s1, v1, _ = self.__light.getHsv() h2, s2, v2, _ = self.__dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) painter.fillRect(rect, QBrush(self.__dark)) sectionSize = 2 if self.__orientation == Qt.Horizontal: numIntervals = rect.width() / sectionSize else: numIntervals = rect.height() / sectionSize section = QRect() for i in range(int(numIntervals)): if self.__orientation == Qt.Horizontal: section.setRect(rect.x() + i * sectionSize, rect.y(), sectionSize, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i * sectionSize, rect.width(), sectionSize) ratio = float(i) / float(numIntervals) color = QColor() color.setHsv( h1 + int(ratio * (h2 - h1) + 0.5), s1 + int(ratio * (s2 - s1) + 0.5), v1 + int(ratio * (v2 - v1) + 0.5) ) painter.fillRect(section, color) painter.restore()
def drawColorBar(self, painter, rect): h1, s1, v1, _ = self.__light.getHsv() h2, s2, v2, _ = self.__dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) painter.fillRect(rect, QBrush(self.__dark)) sectionSize = 2 if (self.__orientation == Qt.Horizontal): numIntervals = rect.width()/sectionSize else: numIntervals = rect.height()/sectionSize section = QRect() for i in range(int(numIntervals)): if self.__orientation == Qt.Horizontal: section.setRect(rect.x() + i*sectionSize, rect.y(), sectionSize, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i*sectionSize, rect.width(), sectionSize) ratio = float(i)/float(numIntervals) color = QColor() color.setHsv(h1 + int(ratio*(h2-h1) + 0.5), s1 + int(ratio*(s2-s1) + 0.5), v1 + int(ratio*(v2-v1) + 0.5)) painter.fillRect(section, color) painter.restore()
def draw(self, painter, xMap, yMap, rect): c = QColor(Qt.white) r = QRect(rect) for i in range(100, 0, -10): r.setBottom(yMap.transform(i - 10)) r.setTop(yMap.transform(i)) painter.fillRect(r, c) c = c.darker(110)
def mousePressEvent(self, event): if event.button() == Qt.LeftButton: if PYQT5: pm = self.grab() else: pm = QPixmap.grabWidget(self) color = QColor() color.setRgb(pm.toImage().pixel(event.x(), event.y())) self.SIG_COLOR_SELECTED.emit(color) event.accept()
def mousePressEvent(self, event): if event.button() == Qt.LeftButton: if PYQT5: pm = self.grab() else: pm = QPixmap.grabWidget(self) color = QColor() color.setRgb(pm.toImage().pixel(event.x(), event.y())) self.colorSelected.emit(color) event.accept()
def __init__(self, *args): QwtPlot.__init__(self, *args) self.setTitle("Interactive Plot") self.setCanvasColor(Qt.darkCyan) grid = QwtPlotGrid() grid.attach(self) grid.setMajorPen(QPen(Qt.white, 0, Qt.DotLine)) self.setAxisScale(QwtPlot.xBottom, 0.0, 100.0) self.setAxisScale(QwtPlot.yLeft, 0.0, 100.0) # Avoid jumping when label with 3 digits # appear/disappear when scrolling vertically scaleDraw = self.axisScaleDraw(QwtPlot.yLeft) scaleDraw.setMinimumExtent(scaleDraw.extent( self.axisWidget(QwtPlot.yLeft).font())) self.plotLayout().setAlignCanvasToScales(True) self.__insertCurve(Qt.Vertical, Qt.blue, 30.0) self.__insertCurve(Qt.Vertical, Qt.magenta, 70.0) self.__insertCurve(Qt.Horizontal, Qt.yellow, 30.0) self.__insertCurve(Qt.Horizontal, Qt.white, 70.0) self.replot() scaleWidget = self.axisWidget(QwtPlot.yLeft) scaleWidget.setMargin(10) self.__colorBar = ColorBar(Qt.Vertical, scaleWidget) self.__colorBar.setRange( QColor(Qt.red), QColor(Qt.darkBlue)) self.__colorBar.setFocusPolicy(Qt.TabFocus) self.__colorBar.colorSelected.connect(self.setCanvasColor) # we need the resize events, to lay out the color bar scaleWidget.installEventFilter(self) # we need the resize events, to lay out the wheel self.canvas().installEventFilter(self) scaleWidget.setWhatsThis( 'Selecting a value at the scale will insert a new curve.') self.__colorBar.setWhatsThis( 'Selecting a color will change the background of the plot.') self.axisWidget(QwtPlot.xBottom).setWhatsThis( 'Selecting a value at the scale will insert a new curve.')
def renderDocument(self, plot, filename, sizeMM=(300, 200), resolution=85, format_=None): if isinstance(sizeMM, tuple): sizeMM = QSizeF(*sizeMM) if format_ is None: ext = osp.splitext(filename)[1] if not ext: raise TypeError( "Unable to determine target format from filename") format_ = ext[1:] if plot is None or sizeMM.isEmpty() or resolution <= 0: return title = plot.title().text() if not title: title = "Plot Document" mmToInch = 1. / 25.4 size = sizeMM * mmToInch * resolution documentRect = QRectF(0.0, 0.0, size.width(), size.height()) fmt = format_.lower() if fmt in ("pdf", "ps"): printer = QPrinter() if fmt == "pdf": printer.setOutputFormat(QPrinter.PdfFormat) else: printer.setOutputFormat(QPrinter.PostScriptFormat) printer.setColorMode(QPrinter.Color) printer.setFullPage(True) printer.setPaperSize(sizeMM, QPrinter.Millimeter) printer.setDocName(title) printer.setOutputFileName(filename) printer.setResolution(resolution) painter = QPainter(printer) self.render(plot, painter, documentRect) painter.end() elif fmt == "svg": generator = QSvgGenerator() generator.setTitle(title) generator.setFileName(filename) generator.setResolution(resolution) generator.setViewBox(documentRect) painter = QPainter(generator) self.render(plot, painter, documentRect) painter.end() elif fmt in QImageWriter.supportedImageFormats(): imageRect = documentRect.toRect() dotsPerMeter = int(round(resolution * mmToInch * 1000.)) image = QImage(imageRect.size(), QImage.Format_ARGB32) image.setDotsPerMeterX(dotsPerMeter) image.setDotsPerMeterY(dotsPerMeter) image.fill(QColor(Qt.white).rgb()) painter = QPainter(image) self.render(plot, painter, imageRect) painter.end() image.save(filename, fmt) else: raise TypeError("Unsupported file format '%s'" % fmt)
def __init__(self, *args): color1, color2 = QColor(Qt.blue), QColor(Qt.yellow) format_ = QwtColorMap.RGB if len(args) == 1: format_, = args elif len(args) == 2: color1, color2 = args elif len(args) == 3: color1, color2, format_ = args elif len(args) != 0: raise TypeError("%s() takes 0, 1, 2 or 3 argument(s) (%s given)"\ % (self.__class__.__name__, len(args))) super(QwtLinearColorMap, self).__init__(format_) self.__data = QwtLinearColorMap_PrivateData() self.__data.mode = self.ScaledColors self.setColorInterval(color1, color2)
def insertCurve(self, axis, base): if axis == QwtPlot.yLeft or axis == QwtPlot.yRight: o = Qt.Horizontal else: o = Qt.Vertical self.__insertCurve(o, QColor(Qt.red), base) self.replot()
def drawColorBar(self, painter, colorMap, interval, scaleMap, orientation, rect): """ Draw a color bar into a rectangle :param QPainter painter: Painter :param qwt.color_map.QwtColorMap colorMap: Color map :param qwt.interval.QwtInterval interval: Value range :param qwt.scalemap.QwtScaleMap scaleMap: Scale map :param Qt.Orientation orientation: Orientation :param QRectF rect: Target rectangle """ colorTable = [] if colorMap.format() == QwtColorMap.Indexed: colorTable = colorMap.colorTable(interval) c = QColor() devRect = rect.toAlignedRect() pixmap = QPixmap(devRect.size()) pixmap.fill(Qt.transparent) pmPainter = QPainter(pixmap) pmPainter.translate(-devRect.x(), -devRect.y()) if orientation == Qt.Horizontal: sMap = QwtScaleMap(scaleMap) sMap.setPaintInterval(rect.left(), rect.right()) for x in range(devRect.left(), devRect.right()+1): value = sMap.invTransform(x) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(x, devRect.top(), x, devRect.bottom()) else: sMap = QwtScaleMap(scaleMap) sMap.setPaintInterval(rect.bottom(), rect.top()) for y in range(devRect.top(), devRect.bottom()+1): value = sMap.invTransform(y) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(devRect.left(), y, devRect.right(), y) pmPainter.end() self.drawPixmap(painter, rect, pixmap)
def __init__(self, *args): QwtPlotItem.__init__(self, *args) self.__attributes = HistogramItem.Auto self.__data = QwtIntervalSeriesData() self.__color = QColor() self.__reference = 0.0 self.setItemAttribute(QwtPlotItem.AutoScale, True) self.setItemAttribute(QwtPlotItem.Legend, True) self.setZ(20.0)
def __init__(self, parent=None): super(TestPlot, self).__init__(parent) self.setWindowTitle("PyQwt" if USE_PYQWT5 else "PythonQwt") self.enableAxis(self.xTop, True) self.enableAxis(self.yRight, True) y = np.linspace(0, 10, 500) curve1 = QwtPlotCurve('Test Curve 1') curve1.setData(np.sin(y), y) curve2 = QwtPlotCurve('Test Curve 2') curve2.setData(y**3, y) if USE_PYQWT5: curve2.setAxis(self.xTop, self.yRight) else: # PythonQwt curve2.setAxes(self.xTop, self.yRight) for item, col, xa, ya in ((curve1, Qt.green, self.xBottom, self.yLeft), (curve2, Qt.red, self.xTop, self.yRight)): if not USE_PYQWT5: # PythonQwt item.setOrientation(Qt.Vertical) item.attach(self) item.setPen(QPen(col)) for axis_id in xa, ya: palette = self.axisWidget(axis_id).palette() palette.setColor(QPalette.WindowText, QColor(col)) palette.setColor(QPalette.Text, QColor(col)) self.axisWidget(axis_id).setPalette(palette) ticks_font = self.axisFont(axis_id) self.setAxisFont(axis_id, ticks_font) self.canvas().setFrameStyle(0) #QFrame.Panel|QFrame.Sunken) self.plotLayout().setCanvasMargin(0) self.axisWidget(QwtPlot.yLeft).setMargin(0) self.axisWidget(QwtPlot.xTop).setMargin(0) self.axisWidget(QwtPlot.yRight).setMargin(0) self.axisWidget(QwtPlot.xBottom).setMargin(0) self.marker = QwtPlotMarker() self.marker.setValue(0, 5) self.marker.attach(self)
def drawColorBar(self, painter, colorMap, interval, scaleMap, orientation, rect): colorTable = [] if colorMap.format() == QwtColorMap.Indexed: colorTable = colorMap.colorTable(interval) c = QColor() devRect = rect.toAlignedRect() pixmap = QPixmap(devRect.size()) pixmap.fill(Qt.transparent) pmPainter = QPainter(pixmap) pmPainter.translate(-devRect.x(), -devRect.y()) if orientation == Qt.Horizontal: sMap = scaleMap sMap.setPaintInterval(rect.left(), rect.right()) for x in range(devRect.left(), devRect.right() + 1): value = sMap.invTransform(x) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(x, devRect.top(), devRect.bottom()) else: sMap = scaleMap sMap.setPaintInterval(rect.bottom(), rect.top()) for y in range(devRect.top(), devRect.bottom() + 1): value = sMap.invTransform(y) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(devRect.left(), y, devRect.right(), y) pmPainter.end() self.drawPixmap(painter, rect, pixmap)
def findAscent(self, font): dummy = "E" white = QColor(Qt.white) fm = self.fontmetrics(font) pm = QPixmap(fm.width(dummy), fm.height()) pm.fill(white) p = QPainter(pm) p.setFont(font) p.drawText(0, 0, pm.width(), pm.height(), 0, dummy) p.end() img = pm.toImage() w = pm.width() linebytes = w*4 for row in range(img.height()): line = img.scanLine(row).asstring(linebytes) for col in range(w): color = struct.unpack('I', line[col*4:(col+1)*4])[0] if color != white.rgb(): return fm.ascent()-row+1 return fm.ascent()
def findAscent(self, font): dummy = "E" white = QColor(Qt.white) fm = self.fontmetrics(font) pm = QPixmap(fm.width(dummy), fm.height()) pm.fill(white) p = QPainter(pm) p.setFont(font) p.drawText(0, 0, pm.width(), pm.height(), 0, dummy) p.end() img = pm.toImage() w = pm.width() linebytes = w * 4 for row in range(img.height()): line = img.scanLine(row).asstring(linebytes) for col in range(w): color = struct.unpack('I', line[col * 4:(col + 1) * 4])[0] if color != white.rgb(): return fm.ascent() - row + 1 return fm.ascent()
def setColor(self, color): """ Set the pen color used for drawing the text. :param QColor color: Color .. note:: Setting the color might have no effect, when the text contains control sequences for setting colors. .. seealso:: :py:meth:`color()`, :py:meth:`usedColor()` """ self.__data.color = QColor(color) self.setPaintAttribute(self.PaintUsingTextColor)
def color(self, interval, value): """ Map a value into a color :param qwt.interval.QwtInterval interval: valid interval for value :param float value: value :return: the color corresponding to value .. warning :: This method is slow for Indexed color maps. If it is necessary to map many values, its better to get the color table once and find the color using `colorIndex()`. """ if self.__format == self.RGB: return QColor.fromRgba(self.rgb(interval, value)) else: index = self.colorIndex(interval, value) return self.colorTable(interval)[index]
def drawColorBar(self, painter, colorMap, interval, scaleMap, orientation, rect): """ Draw a color bar into a rectangle :param QPainter painter: Painter :param qwt.color_map.QwtColorMap colorMap: Color map :param qwt.interval.QwtInterval interval: Value range :param qwt.scalemap.QwtScaleMap scaleMap: Scale map :param Qt.Orientation orientation: Orientation :param QRectF rect: Target rectangle """ colorTable = [] if colorMap.format() == QwtColorMap.Indexed: colorTable = colorMap.colorTable(interval) c = QColor() devRect = rect.toAlignedRect() pixmap = QPixmap(devRect.size()) pixmap.fill(Qt.transparent) pmPainter = QPainter(pixmap) pmPainter.translate(-devRect.x(), -devRect.y()) if orientation == Qt.Horizontal: sMap = QwtScaleMap(scaleMap) sMap.setPaintInterval(rect.left(), rect.right()) for x in range(devRect.left(), devRect.right() + 1): value = sMap.invTransform(x) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(x, devRect.top(), x, devRect.bottom()) else: sMap = QwtScaleMap(scaleMap) sMap.setPaintInterval(rect.bottom(), rect.top()) for y in range(devRect.top(), devRect.bottom() + 1): value = sMap.invTransform(y) if colorMap.format() == QwtColorMap.RGB: c.setRgba(colorMap.rgb(interval, value)) else: c = colorTable[colorMap.colorIndex(interval, value)] pmPainter.setPen(c) pmPainter.drawLine(devRect.left(), y, devRect.right(), y) pmPainter.end() self.drawPixmap(painter, rect, pixmap)
def color(self, interval, value): if self.__format == self.RGB: return QColor.fromRgba(self.rgb(interval, value)) else: index = self.colorIndex(interval, value) return self.colorTable(interval)[index]
def setColor(self, color): self.__data.color = QColor(color) self.setPaintAttribute(self.PaintUsingTextColor)
def __init__(self, *args): # colors = [Qt.Qt.red, Qt.Qt.yellow, Qt.Qt.green, Qt.Qt.blue, Qt.Qt.cyan, Qt.Qt.magenta, Qt.Qt.gray, Qt.Qt.white, # Qt.Qt.darkRed, Qt.Qt.darkYellow, Qt.Qt.darkGreen, Qt.Qt.darkBlue, Qt.Qt.darkCyan, # Qt.Qt.darkMagenta, Qt.Qt.lightGray, Qt.Qt.darkGray] #colors = [Qt.red, Qt.darkRed, Qt.green, Qt.darkGreen, Qt.blue, # Qt.darkBlue, Qt.cyan, Qt.darkCyan, Qt.magenta, # Qt.darkMagenta, Qt.yellow, Qt.darkYellow, Qt.gray, # Qt.darkGray, Qt.lightGray, Qt.black] colors = [ QColor('#CC0000'), QColor('#FF3333'), QColor('#CC6600'), QColor('#FF9933'), QColor('#CCCC00'), QColor('#FFFF33'), QColor('#66CC00'), QColor('#00CCCC'), QColor('#33FFFF'), QColor('#0066CC'), QColor('#3399FF'), QColor('#3399FF'), QColor('#0000CC'), QColor('#6600CC'), QColor('#9933FF'), QColor('#CC00CC'), QColor('#FF33FF'), QColor('#CC0066'), QColor('#FF3399'), QColor('#C0C0C0') ] QwtPlot.__init__(self, *args) self.setCanvasBackground(Qt.black) self.alignScales() # grid self.grid = QwtPlotGrid() self.grid.attach(self) self.grid.setPen(QPen(Qt.white, 0, Qt.DotLine)) # setting axis title. The yLeft axis title can chance to 'Temperature', depending on plot preferences self.setAxisTitle(QwtPlot.xBottom, 'Time [hh:mm:ss]') self.setAxisTitle(QwtPlot.yLeft, 'Height [mm]') # Habilita e denomina eixo Y2 self.enableAxis(QwtPlot.yRight) self.setAxisTitle(QwtPlot.yRight, 'Temperature[ºC]') self.nplots = 40 self.Plots = np.array([]) self.Data = np.array([]) for i in range(self.nplots): self.Plots = np.append(self.Plots, QwtPlotCurve()) if (i % 2 == 0): pen = QPen(colors[int(i / 2)], 1, Qt.SolidLine) else: pen = QPen(colors[int(i / 2)], 1, Qt.DashLine) self.Plots[i].setPen(pen) self.Plots[i].attach(self) """define como valor plotado será escrito no eixo x""" self.setAxisScaleDraw(QwtPlot.xBottom, TimeScaleDraw()) self.Data = np.append(self.Data, dataclass()) if divmod(i, 2)[1] == 1: self.Plots[i].setYAxis(QwtPlot.yRight) # define a tupple that will contain plot data, expressed in cartesian coordinates self.Plots[i].setData(self.Data[i].x, self.Data[i].y) # legend # self.legend = QwtLegend() # self.legend.setFrameStyle(QFrame.Box) self.insertLegend(QwtLegend(), QwtPlot.BottomLegend) # replot self.replot() # zoom # self.zoomer = QwtPlotZoomer(QwtPlot.xBottom, # QwtPlot.yLeft, # QwtPicker.DragSelection, # QwtPicker.AlwaysOn, # self.canvas()) # # self.zoomer.setRubberBandPen(QPen(Qt.green)) self.startTimer(50)
def drawRoundedFrame(self, painter, rect, xRadius, yRadius, palette, lineWidth, frameStyle): painter.save() painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(Qt.NoBrush) lw2 = lineWidth * .5 r = rect.adjusted(lw2, lw2, -lw2, -lw2) path = QPainterPath() path.addRoundedRect(r, xRadius, yRadius) Plain, Sunken, Raised = list(range(3)) style = Plain if (frameStyle & QFrame.Sunken) == QFrame.Sunken: style = Sunken if (frameStyle & QFrame.Raised) == QFrame.Raised: style = Raised if style != Plain and path.elementCount() == 17: pathList = [QPainterPath() for _i in range(8)] for i in range(4): j = i * 4 + 1 pathList[2 * i].moveTo( path.elementAt(j - 1).x, path.elementAt(j - 1).y) pathList[2 * i].cubicTo( path.elementAt(j + 0).x, path.elementAt(j + 0).y, path.elementAt(j + 1).x, path.elementAt(j + 1).y, path.elementAt(j + 2).x, path.elementAt(j + 2).y) pathList[2 * i + 1].moveTo( path.elementAt(j + 2).x, path.elementAt(j + 2).y) pathList[2 * i + 1].lineTo( path.elementAt(j + 3).x, path.elementAt(j + 3).y) c1 = QColor(palette.color(QPalette.Dark)) c2 = QColor(palette.color(QPalette.Light)) if style == Raised: c1, c2 = c2, c1 for i in range(5): r = pathList[2 * i].controlPointRect() arcPen = QPen() arcPen.setCapStyle(Qt.FlatCap) arcPen.setWidth(lineWidth) linePen = QPen() linePen.setCapStyle(Qt.FlatCap) linePen.setWidth(lineWidth) if i == 0: arcPen.setColor(c1) linePen.setColor(c1) elif i == 1: gradient = QLinearGradient() gradient.setStart(r.topLeft()) gradient.setFinalStop(r.bottomRight()) gradient.setColorAt(0., c1) gradient.setColorAt(1., c2) arcPen.setBrush(gradient) linePen.setColor(c2) elif i == 2: arcPen.setColor(c2) linePen.setColor(c2) elif i == 3: gradient = QLinearGradient() gradient.setStart(r.bottomRight()) gradient.setFinalStop(r.topLeft()) gradient.setColorAt(0., c2) gradient.setColorAt(1., c1) arcPen.setBrush(gradient) linePen.setColor(c1) painter.setPen(arcPen) painter.drawPath(pathList[2 * i]) painter.setPen(linePen) painter.drawPath(pathList[2 * i + 1]) else: pen = QPen(palette.color(QPalette.WindowText), lineWidth) painter.setPen(pen) painter.drawPath(path) painter.restore()
class ColorBar(QWidget): colorSelected = Signal(QColor) def __init__(self, orientation, *args): QWidget.__init__(self, *args) self.__orientation = orientation self.__light = QColor(Qt.white) self.__dark = QColor(Qt.black) self.setCursor(Qt.PointingHandCursor) def setOrientation(self, orientation): self.__orientation = orientation self.update() def orientation(self): return self.__orientation def setRange(self, light, dark): self.__light = light self.__dark = dark self.update() def setLight(self, color): self.__light = color self.update() def setDark(self, color): self.__dark = color self.update() def light(self): return self.__light def dark(self): return self.__dark def mousePressEvent(self, event): if event.button() == Qt.LeftButton: if PYQT5: pm = self.grab() else: pm = QPixmap.grabWidget(self) color = QColor() color.setRgb(pm.toImage().pixel(event.x(), event.y())) self.colorSelected.emit(color) event.accept() def paintEvent(self, _): painter = QPainter(self) self.drawColorBar(painter, self.rect()) def drawColorBar(self, painter, rect): h1, s1, v1, _ = self.__light.getHsv() h2, s2, v2, _ = self.__dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) painter.fillRect(rect, QBrush(self.__dark)) sectionSize = 2 if (self.__orientation == Qt.Horizontal): numIntervals = rect.width()/sectionSize else: numIntervals = rect.height()/sectionSize section = QRect() for i in range(int(numIntervals)): if self.__orientation == Qt.Horizontal: section.setRect(rect.x() + i*sectionSize, rect.y(), sectionSize, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i*sectionSize, rect.width(), sectionSize) ratio = float(i)/float(numIntervals) color = QColor() color.setHsv(h1 + int(ratio*(h2-h1) + 0.5), s1 + int(ratio*(s2-s1) + 0.5), v1 + int(ratio*(v2-v1) + 0.5)) painter.fillRect(section, color) painter.restore()
def color2(self): return QColor(self.__data.colorStops.rgb(self.__data.mode, 1.))
class ColorBar(QWidget): SIG_COLOR_SELECTED = Signal(QColor) def __init__(self, orientation, *args): QWidget.__init__(self, *args) self.__orientation = orientation self.__light = QColor(Qt.white) self.__dark = QColor(Qt.black) self.setCursor(Qt.PointingHandCursor) def setOrientation(self, orientation): self.__orientation = orientation self.update() def orientation(self): return self.__orientation def setRange(self, light, dark): self.__light = light self.__dark = dark self.update() def setLight(self, color): self.__light = color self.update() def setDark(self, color): self.__dark = color self.update() def light(self): return self.__light def dark(self): return self.__dark def mousePressEvent(self, event): if event.button() == Qt.LeftButton: if PYQT5: pm = self.grab() else: pm = QPixmap.grabWidget(self) color = QColor() color.setRgb(pm.toImage().pixel(event.x(), event.y())) self.SIG_COLOR_SELECTED.emit(color) event.accept() def paintEvent(self, _): painter = QPainter(self) self.drawColorBar(painter, self.rect()) def drawColorBar(self, painter, rect): h1, s1, v1, _ = self.__light.getHsv() h2, s2, v2, _ = self.__dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) painter.fillRect(rect, QBrush(self.__dark)) sectionSize = 2 if self.__orientation == Qt.Horizontal: numIntervals = rect.width() / sectionSize else: numIntervals = rect.height() / sectionSize section = QRect() for i in range(int(numIntervals)): if self.__orientation == Qt.Horizontal: section.setRect(rect.x() + i * sectionSize, rect.y(), sectionSize, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i * sectionSize, rect.width(), sectionSize) ratio = float(i) / float(numIntervals) color = QColor() color.setHsv( h1 + int(ratio * (h2 - h1) + 0.5), s1 + int(ratio * (s2 - s1) + 0.5), v1 + int(ratio * (v2 - v1) + 0.5) ) painter.fillRect(section, color) painter.restore()
def setColorInterval(self, color1, color2): self.__data.colorStops = ColorStops() self.__data.colorStops.insert(0., QColor(color1)) self.__data.colorStops.insert(1., QColor(color2))
def construct_selectors(self, array_shape=None, axis_label=None, axis_parms=None): """ construct a group of AxisRange objects. These objects allow the user to specify which dimensions of an N-dimensional array are viewable in a 2 or 3-D display """ self.green = QColor(0, 0, 0) self.green.setGreen(255) self.red = QColor(0, 0, 0) self.red.setRed(255) self.axis_parms = axis_parms # add control buttons and AxisRange selectors self.buttons = [] self.button_number = [] self.axis_controllers = [] if array_shape is None: array_shape = [] for i in range(len(axis_label)): array_shape.append(axis_parms[axis_label[i]][3]) self.rank = 0 for i in range(len(array_shape)): if array_shape[i] > 1: self.rank = self.rank + 1 self.active_axes = {} self.num_selectors = -1 row = 0 col = 0 for i in range(len(array_shape)): if array_shape[i] > 1: self.num_selectors = self.num_selectors + 1 # add buttons button_label = None if not axis_label == None: button_label = axis_label[i] else: button_label = 'axis ' + str(i) if self.axis_parms is None: parms = None else: if axis_label[i] in self.axis_parms: parms = self.axis_parms[axis_label[i]] else: parms = None self.axis_controllers.append( AxisRange(ax_number=self.num_selectors, axis_parms=parms, parent=self)) self.axis_controllers[self.num_selectors].setLabel( button_label) self.axis_controllers[self.num_selectors].setRange( array_shape[i]) if self.num_selectors <= self.rank - (self.selectable_axes + 1): self.axis_controllers[self.num_selectors].setSliderColor( self.green) self.axis_controllers[self.num_selectors].setActive(True) self.axis_controllers[self.num_selectors].resetValue() self.axis_controllers[self.num_selectors].show_display() else: self.axis_controllers[self.num_selectors].setSliderColor( self.red) self.axis_controllers[self.num_selectors].hide_display() self.axis_controllers[self.num_selectors].axis_number.connect( self.defineAxes) self.axis_controllers[ self.num_selectors].Value_Changed.connect(self.update) if col == 0: spacer = QSpacerItem(22, 9, QSizePolicy.Expanding, QSizePolicy.Minimum) self.layout.addItem(spacer, row, col) col = col + 1 self.layout.addWidget( self.axis_controllers[self.num_selectors], row, col) self.buttons.append( self.axis_controllers[self.num_selectors].getButton()) self.button_number.append(i) # self.buttons[self.num_selectors].setToggleButton(True) if self.num_selectors <= self.rank - (self.selectable_axes + 1): self.axis_controllers[self.num_selectors].setOn(False) else: self.axis_controllers[self.num_selectors].setOn(True) self.active_axes[self.num_selectors] = True if col >= 4: col = 0 row = row + 1 else: col = col + 1 # add one to get number of active selector buttons self.num_selectors = self.num_selectors + 1
class ND_Controller(QWidget): defineSelectedAxes = pyqtSignal(int, int, int) sliderValueChanged = pyqtSignal(int, int, str) def __init__(self, array_shape=None, axis_label=None, axis_parms=None, num_axes=2, parent=None, name=""): QWidget.__init__(self, parent) # set default number of selectable axes to use 2-D QWT-based display self.selectable_axes = num_axes # create grid layout self.layout = QGridLayout(self) self.setWhatsThis(controller_instructions) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) self.construct_selectors(array_shape, axis_label, axis_parms) # __init__() def construct_selectors(self, array_shape=None, axis_label=None, axis_parms=None): """ construct a group of AxisRange objects. These objects allow the user to specify which dimensions of an N-dimensional array are viewable in a 2 or 3-D display """ self.green = QColor(0, 0, 0) self.green.setGreen(255) self.red = QColor(0, 0, 0) self.red.setRed(255) self.axis_parms = axis_parms # add control buttons and AxisRange selectors self.buttons = [] self.button_number = [] self.axis_controllers = [] if array_shape is None: array_shape = [] for i in range(len(axis_label)): array_shape.append(axis_parms[axis_label[i]][3]) self.rank = 0 for i in range(len(array_shape)): if array_shape[i] > 1: self.rank = self.rank + 1 self.active_axes = {} self.num_selectors = -1 row = 0 col = 0 for i in range(len(array_shape)): if array_shape[i] > 1: self.num_selectors = self.num_selectors + 1 # add buttons button_label = None if not axis_label == None: button_label = axis_label[i] else: button_label = 'axis ' + str(i) if self.axis_parms is None: parms = None else: if axis_label[i] in self.axis_parms: parms = self.axis_parms[axis_label[i]] else: parms = None self.axis_controllers.append( AxisRange(ax_number=self.num_selectors, axis_parms=parms, parent=self)) self.axis_controllers[self.num_selectors].setLabel( button_label) self.axis_controllers[self.num_selectors].setRange( array_shape[i]) if self.num_selectors <= self.rank - (self.selectable_axes + 1): self.axis_controllers[self.num_selectors].setSliderColor( self.green) self.axis_controllers[self.num_selectors].setActive(True) self.axis_controllers[self.num_selectors].resetValue() self.axis_controllers[self.num_selectors].show_display() else: self.axis_controllers[self.num_selectors].setSliderColor( self.red) self.axis_controllers[self.num_selectors].hide_display() self.axis_controllers[self.num_selectors].axis_number.connect( self.defineAxes) self.axis_controllers[ self.num_selectors].Value_Changed.connect(self.update) if col == 0: spacer = QSpacerItem(22, 9, QSizePolicy.Expanding, QSizePolicy.Minimum) self.layout.addItem(spacer, row, col) col = col + 1 self.layout.addWidget( self.axis_controllers[self.num_selectors], row, col) self.buttons.append( self.axis_controllers[self.num_selectors].getButton()) self.button_number.append(i) # self.buttons[self.num_selectors].setToggleButton(True) if self.num_selectors <= self.rank - (self.selectable_axes + 1): self.axis_controllers[self.num_selectors].setOn(False) else: self.axis_controllers[self.num_selectors].setOn(True) self.active_axes[self.num_selectors] = True if col >= 4: col = 0 row = row + 1 else: col = col + 1 # add one to get number of active selector buttons self.num_selectors = self.num_selectors + 1 def showDisplay(self, show_self): if show_self > 0: self.show() else: self.hide() # showDisplay def set_num_selectable_axes(self, num_axes=2): self.selectable_axes = num_axes self.redefineAxes() def get_num_selectors(self): """ gets number of AxisRange objects in the Controller """ return self.num_selectors def defineAxes(self, button_id, do_on=False): """ When a button is pressed, this function figures out if the user has selected the required number of dimensions for extraction. The AxisRange objects for those dimensions are colored red. All data for the selected dimensions will be displayed. The remaining AxisRange objects are colored green - they enable the user to select a single value from their associated dimension. """ # print 'defineAxes button id = ', button_id if not self.active_axes is None and len( self.active_axes) == self.selectable_axes: self.resetAxes() self.axis_controllers[button_id].setOn(True) # if do_on: # self.axis_controllers[button_id].setOn(True) if self.axis_controllers[button_id].isOn(): self.axis_controllers[button_id].setSliderColor(self.red) # self.axis_controllers[button_id].hide_display() self.active_axes[button_id] = True if len(self.active_axes) == self.selectable_axes: first_axis = None second_axis = None third_axis = None for i in range(self.num_selectors): if i in self.active_axes: if first_axis is None: first_axis = self.button_number[i] elif second_axis is None: second_axis = self.button_number[i] else: if self.selectable_axes == 3: if third_axis is None: third_axis = self.button_number[i] self.axis_controllers[i].setSliderColor(self.red) self.axis_controllers[i].setActive(False) self.axis_controllers[i].hide_display() else: self.axis_controllers[i].setSliderColor(self.green) self.axis_controllers[i].setActive(True) self.axis_controllers[i].show_display() self.axis_controllers[i].resetValue() self.defineSelectedAxes.emit(first_axis, second_axis, third_axis) else: if button_id in self.active_axes: del self.active_axes[button_id] self.axis_controllers[button_id].setSliderColor(self.red) # self.axis_controllers[button_id].hide_display() # defineAxes def redefineAxes(self): self.defineAxes(self.num_selectors - 1, True) self.defineAxes(self.num_selectors - 2, True) # redefineAxes def resetAxes(self): """ resets all AxisRange objects to be inactive """ for i in range(self.num_selectors): self.axis_controllers[i].setOn(False) self.axis_controllers[i].setSliderColor(self.red) self.axis_controllers[i].setActive(False) # self.axis_controllers[i].hide_display() self.axis_controllers[i].resetValue() self.active_axes = {} # resetAxes def update(self, axis_number, slider_value, display_string): """ emits a signal to the data selection program giving the new value of an active dimension index """ print('Caught ', axis_number, slider_value, display_string) if not axis_number in self.active_axes: if not self.axis_controllers[axis_number].isOn(): self.sliderValueChanged.emit(self.button_number[axis_number], slider_value, display_string) else: self.axis_controllers[axis_number].resetValue() else: self.axis_controllers[axis_number].resetValue()
def __init__(self, orientation, *args): QWidget.__init__(self, *args) self.__orientation = orientation self.__light = QColor(Qt.white) self.__dark = QColor(Qt.black) self.setCursor(Qt.PointingHandCursor)
def setColor(self, color): c = QColor(color) c.setAlpha(150) self.setPen(c) self.setBrush(c)
def drawRoundedFrame(self, painter, rect, xRadius, yRadius, palette, lineWidth, frameStyle): """ Draw a rectangular frame with rounded borders :param QPainter painter: Painter :param QRectF rect: Frame rectangle :param float xRadius: x-radius of the ellipses defining the corners :param float yRadius: y-radius of the ellipses defining the corners :param QPalette palette: `QPalette.WindowText` is used for plain borders, `QPalette.Dark` and `QPalette.Light` for raised or sunken borders :param int lineWidth: Line width :param int frameStyle: bitwise OR´ed value of `QFrame.Shape` and `QFrame.Shadow` """ painter.save() painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(Qt.NoBrush) lw2 = lineWidth * .5 r = rect.adjusted(lw2, lw2, -lw2, -lw2) path = QPainterPath() path.addRoundedRect(r, xRadius, yRadius) Plain, Sunken, Raised = list(range(3)) style = Plain if (frameStyle & QFrame.Sunken) == QFrame.Sunken: style = Sunken if (frameStyle & QFrame.Raised) == QFrame.Raised: style = Raised if style != Plain and path.elementCount() == 17: pathList = [QPainterPath() for _i in range(8)] for i in range(4): j = i * 4 + 1 pathList[2 * i].moveTo( path.elementAt(j - 1).x, path.elementAt(j - 1).y) pathList[2 * i].cubicTo( path.elementAt(j + 0).x, path.elementAt(j + 0).y, path.elementAt(j + 1).x, path.elementAt(j + 1).y, path.elementAt(j + 2).x, path.elementAt(j + 2).y) pathList[2 * i + 1].moveTo( path.elementAt(j + 2).x, path.elementAt(j + 2).y) pathList[2 * i + 1].lineTo( path.elementAt(j + 3).x, path.elementAt(j + 3).y) c1 = QColor(palette.color(QPalette.Dark)) c2 = QColor(palette.color(QPalette.Light)) if style == Raised: c1, c2 = c2, c1 for i in range(5): r = pathList[2 * i].controlPointRect() arcPen = QPen() arcPen.setCapStyle(Qt.FlatCap) arcPen.setWidth(lineWidth) linePen = QPen() linePen.setCapStyle(Qt.FlatCap) linePen.setWidth(lineWidth) if i == 0: arcPen.setColor(c1) linePen.setColor(c1) elif i == 1: gradient = QLinearGradient() gradient.setStart(r.topLeft()) gradient.setFinalStop(r.bottomRight()) gradient.setColorAt(0., c1) gradient.setColorAt(1., c2) arcPen.setBrush(gradient) linePen.setColor(c2) elif i == 2: arcPen.setColor(c2) linePen.setColor(c2) elif i == 3: gradient = QLinearGradient() gradient.setStart(r.bottomRight()) gradient.setFinalStop(r.topLeft()) gradient.setColorAt(0., c2) gradient.setColorAt(1., c1) arcPen.setBrush(gradient) linePen.setColor(c1) painter.setPen(arcPen) painter.drawPath(pathList[2 * i]) painter.setPen(linePen) painter.drawPath(pathList[2 * i + 1]) else: pen = QPen(palette.color(QPalette.WindowText), lineWidth) painter.setPen(pen) painter.drawPath(path) painter.restore()
def addColorStop(self, value, color): if value >= 0. and value <= 1.: self.__data.colorStops.insert(value, QColor(color))
def setColor(self, color): c = QColor(color) self.setPen(c)