def get_font_array(sz, chars=DEFAULT_CHARS): from guidata.qt.QtGui import QFont, QPainter, QColor font = QFont() font.setFixedPitch(True) font.setPixelSize(sz) font.setStyleStrategy(QFont.NoAntialias) dummy = QImage(10, 10, QImage.Format_ARGB32) pnt = QPainter(dummy) pnt.setFont(font) metric = pnt.fontMetrics() rct = metric.boundingRect(chars) pnt.end() h = rct.height() w = rct.width() img = QImage(w, h, QImage.Format_ARGB32) paint = QPainter() paint.begin(img) paint.setFont(font) paint.setBrush( QColor(255, 255, 255) ) paint.setPen( QColor(255, 255, 255) ) paint.drawRect(0, 0, w+1, h+1) paint.setPen( QColor(0, 0, 0)) paint.setBrush( QColor(0, 0, 0) ) paint.drawText(0, paint.fontMetrics().ascent(), chars) paint.end() try: data = img.bits().asstring(img.numBytes()) except SystemError: # Python 3 return npy = np.frombuffer(data, np.uint8) npy.shape = img.height(), img.bytesPerLine()/4, 4 return npy[:,:, 0]
def __init__(self, parent, ytitle="Y", inity=1000): # self.curve_vlf = make.curve( [ ], [ ], '(Curve Name)', QColor( 255, 0, 0 ), shade=0.5 ) # self.curve_lf = make.curve( [ ], [ ], '(Curve Name)', QColor( 0, 255, 0 ), shade=0.5 ) # self.curve_hf = make.curve( [ ], [ ], '(Curve Name)', QColor( 0, 0, 255 ), shade=0.5 ) self.psdcurve = make.curve( [ ], [ ], '(Curve Name)', QColor( 160, 160, 160 ), shade=0.2 ) def buildrect(x1, x2, filler): rect = RectangleShape(x1, 0., x2, inity) rect.brush.setStyle( Qt.SolidPattern ) rect.brush.setColor( filler ) rect.pen.setStyle( Qt.NoPen ) return rect self.dockwidget = myDockableWidget(parent, CurveWidget, toolbar=True ) # self.plot = self.curvewidget.get_plot() self.plot = self.dockwidget.widget.plot # self.plot.add_item( self.curve_vlf ) # self.plot.add_item( self.curve_lf ) # self.plot.add_item( self.curve_hf ) alpha = 100 self.plot.add_item( buildrect(0.,0.04, QColor(255,178,178,alpha)) ) self.plot.add_item( buildrect(0.04,0.15, QColor(178,178,255,alpha)) ) self.plot.add_item( buildrect(0.15,0.5, QColor(255,255,178,alpha)) ) self.plot.add_item( self.psdcurve ) self.plot.set_antialiasing( True ) self.plot.set_axis_title( QwtPlot.xBottom, 'Frequency' ) self.plot.set_axis_unit( QwtPlot.xBottom, 'Hz' ) self.plot.set_axis_title( QwtPlot.yLeft, ytitle ) self.plot.set_axis_unit( QwtPlot.yLeft, 's^2/Hz' ) #self.plot.setAxisScale(QwtPlot.xBottom, 0, 0.5) self.plot.set_axis_limits( QwtPlot.xBottom, 0, 0.5 )
def set_axis_color(self, axis_id, color): """ Set axis color color: color name (string) or QColor instance """ axis_id = self.get_axis_id(axis_id) if is_text_string(color): color = QColor(color) self.axes_styles[axis_id].color = str(color.name()) self.update_axis_style(axis_id)
def logmessage( self, text, msgtype='info' ): """ Print a message in the message window """ if msgtype == 'error': self.logarea.widget.setTextColor( QColor( 255, 0, 0 ) ) else: self.logarea.widget.setTextColor( QColor( 0, 0, 0 ) ) self.logarea.widget.insertPlainText( text + "\n" ) sb = self.logarea.widget.verticalScrollBar() sb.setValue( sb.maximum() )
def text_to_qcolor(text): """Create a QColor from specified string""" color = QColor() if not is_text_string(text): # testing for QString (PyQt API#1) text = str(text) if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def text_to_qcolor(text): """Create a QColor from specified string""" color = QColor() if not is_text_string(text): # testing for QString (PyQt API#1) text = str(text) if text.startswith('#') and len(text) == 7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def get_brush(conf, section, option="", color="black", alpha=1.0): """ Construct a QBrush from the specified configuration file entry conf: UserConfig instance section [, option]: configuration entry [color]: default color [alpha]: default alpha-channel """ if 'brush' not in option: option += '/brush' color = conf.get(section, option+"/color", color) color = QColor(color) alpha = conf.get(section, option+"/alphaF", alpha) color.setAlphaF(alpha) return QBrush(color)
def __init__(self): QMainWindow.__init__(self) self.setWindowIcon(get_icon(os.path.join(APP_RESOURCES, 'icons', 'python.png'))) self.setupUi(self) # Redirect output to GUI's QTextEdit sys.stdout = OutLog(self.outputTextEdit, sys.stdout) sys.stderr = OutLog(self.outputTextEdit, sys.stderr, QColor(255,0,0) ) settings = QSettings() size = settings.value("MainWindow/Size", QVariant(QSize(600, 500))).toSize() self.resize(size) position = settings.value("MainWindow/Position", QVariant(QPoint(0, 0))).toPoint() self.move(position) self.restoreState( settings.value("MainWindow/State").toByteArray()) self.logger = Logger('Zupport.GUIloader') self.logger.debugging = settings.value("Logging/debugging").toBool() # Set up a ZupportManager to deal with the plugins self.manager = Manager(self) self.plugins = {} # Set up the extents menu self.extent = ExtentContainer() self.menuExtent = QMenu("Extent") resolutions = self.extent.resolutions self.extenactiongroup = QActionGroup(self.menuExtent) noneaction = QAction("None", self.menuExtent) self.extenactiongroup.addAction(noneaction) self.menuExtent.addAction(noneaction) for resolution in resolutions: resolution_text = str(resolution) submenu = self.menuExtent.addMenu(resolution_text) self.menuExtent.addMenu(submenu) for area in self.extent.get_names(resolution): subaction = QAction(str(area) + ": %s" % resolution_text, submenu) subaction.setCheckable(True) self.extenactiongroup.addAction(subaction) submenu.addAction(subaction) noneaction.isChecked() self.menuSettings.addMenu(self.menuExtent) self.actionDebugging_messages.setChecked(self.logger.debugging) self.setWindowTitle("Zupport GUI") self.load_tools() self.toolTreeWidget.itemSelectionChanged.connect(self.update_ui) self.actionDebugging_messages.toggled.connect(self._set_debugging) self.menuExtent.triggered.connect(self.update_ui) self.actionLoad_tool.triggered.connect(self.show_tool_gui) self.toolTreeWidget.doubleClicked.connect(self.show_tool_gui)
def _setup_layout(self): # Allow dockable widgets to be side by side self.setDockOptions(QMainWindow.AnimatedDocks | QMainWindow.AllowNestedDocks) self.setGeometry(300,100,1500,900) self.rrplot = RealTimePlot( self, 'RR-Interval', 'ms', QColor( 255, 0, 0 ) ) self.bwplot = RealTimePlot( self, 'Breathing','', QColor( 0, 0, 255 ) ) self.ecgplot = RealTimePlot( self, 'ECG Waveform','', QColor( 0, 0, 255 ) ) self.logarea = myDockableWidget(self, QTextEdit) self.bwpsd = RealTimePSD( self, 'Breathing PSD', inity=25000 ) self.rrpsd = RealTimePSD( self, 'RR-Interval PSD') self.logarea.widget.setReadOnly( True ) self.logarea.widget.setFont( QFont("Courier", 8) ) self.logarea.widget.setMinimumHeight(150) # Add the DockWidget to the main window self.ecgplot_dock = self.add_dockwidget( self.ecgplot.dockwidget, _("ECG Waveform") ) self.rrcurve_dock = self.add_dockwidget( self.rrplot.dockwidget, _("RR-Intervals Plot") ) self.rrpsd_dock = self.add_dockwidget( self.rrpsd.dockwidget, _("RRI PSD")) self.bwcurve_dock = self.add_dockwidget( self.bwplot.dockwidget, _("Breathing Plot") ) self.bwpsd_dock = self.add_dockwidget( self.bwpsd.dockwidget, _("Breathing PSD (not implemented)") ) self.splitDockWidget(self.rrcurve_dock, self.rrpsd_dock, Qt.Horizontal) self.splitDockWidget(self.bwcurve_dock, self.bwpsd_dock, Qt.Horizontal) self.log_dock = self.add_dockwidget( self.logarea, _("Messages"), position=Qt.BottomDockWidgetArea) #self.splitDockWidget(self.rrcurve_dock, self.ecgplot_dock, Qt.Horizontal) # setting the name of the dock widget is required to save correclty # the postion of the widget when the application close self.rrcurve_dock.setObjectName('rrcurve_dock') self.rrpsd_dock.setObjectName('rrpsd_dock') self.bwcurve_dock.setObjectName('bwcurve_dock') self.bwpsd_dock.setObjectName('bwpsd_dock') self.log_dock.setObjectName('log_dock') self.ecgplot_dock.setObjectName('ecgplot_dock') #self.log_dock.setMinimumHeight( 20 ) self.rrcurve_dock.setMinimumSize( 400, 200 ) self.bwcurve_dock.setMinimumSize( 400, 200 ) self.rrpsd_dock.setMinimumSize( 400, 200 ) self.bwpsd_dock.setMinimumSize( 400, 200 ) self.log_dock.setMinimumSize( 400, 100 ) self.log_dock.setMaximumHeight( 250 )
def __init__(self, parent): tabs = parent.sp r = range(len(tabs)) # Prepare unique names in ugly manner self.names = [n.spec.name for n in tabs] if tabs[0].spec is not None else [''] test = [] for n in r: if self.names.count(self.names[n]) > 1 or self.names[n] in test: test.append(self.names[n]) self.names[n] += ' {}'.format(test.count(self.names[n])) plots = [[ { 'name': 'Calibrated', 'curves': ['Calibrated ' + self.names[n] for n in r] }, { 'name': 'Integrated', 'curves': ['Integrated ' + self.names[n] for n in r] }, { 'name': 'System noise', 'curves': ['Noise ' + self.names[n] for n in r] }, ]] df = [n.axisLimits[1] - n.axisLimits[0] for n in tabs] df2 = max(df) / 2 axisLimits = [ -df2, df2, min([n.axisLimits[2] for n in tabs]), max([n.axisLimits[3] for n in tabs]) ] PlotPanel.__init__(self, parent=parent, plots=plots, axisLimits=axisLimits) self.tabs = tabs cmap = get_cmap('tab10', len(tabs)) self.colors = [ QPen(QColor(x[0] * 255, x[1] * 255, x[2] * 255), 1) for x in cmap.colors ] cPanel = self.curves['Calibrated ' + self.names[0]].parent cPanel.add_item(make.legend("BL")) cPanel.setActive() cPanel = self.curves['Integrated ' + self.names[0]].parent cPanel.add_item(make.legend("BL")) cPanel.setActive() cPanel = self.curves['Noise ' + self.names[0]].parent cPanel.add_item(make.legend("BL")) cPanel.setActive()
def get(self): """Override AbstractDataSetWidget method""" value = self.item.get() if value is not None: color = QColor(value) self.picture = QPicture() painter = QPainter() painter.begin(self.picture) painter.fillRect(QRect(0, 0, 60, 20), QBrush(color)) painter.end() self.group.setPicture(self.picture)
def draw(self, painter, xMap, yMap, canvasRect): self.update_text() x, y = self.get_top_left(xMap, yMap, canvasRect) x0, y0 = self.get_origin(xMap, yMap, canvasRect) painter.save() self.marker.drawSymbols(painter, [QPointF(x0, y0)]) painter.restore() sz = self.text.size() self.draw_frame(painter, x, y, sz.width(), sz.height()) painter.setPen(QPen(QColor(self.labelparam.color))) painter.translate(x, y) self.text.drawContents(painter)
def _setup_colormap(cmap, cmdata): """Setup a QwtLinearColorMap according to matplotlib's data """ red = array(cmdata["red"]) green = array(cmdata["green"]) blue = array(cmdata["blue"]) qmin = QColor() qmin.setRgbF(red[ 0, 2], green[ 0, 2], blue[ 0, 2]) qmax = QColor() qmax.setRgbF(red[-1, 2], green[-1, 2], blue[-1, 2]) cmap.setColorInterval( qmin, qmax ) indices = sorted(set(red[:, 0]) | set(green[:, 0]) | set(blue[:, 0])) for i in indices[1:-1]: idxr = red[:, 0].searchsorted(i) idxg = green[:, 0].searchsorted(i) idxb = blue[:, 0].searchsorted(i) compr = _interpolate(i, red[idxr-1], red[idxr]) compg = _interpolate(i, green[idxg-1], green[idxg]) compb = _interpolate(i, blue[idxb-1], blue[idxb] ) col = QColor() col.setRgbF(compr, compg, compb) cmap.addColorStop(i, col)
def get_pen(conf, section, option="", color="black", width=1, style='SolidLine'): """ Construct a QPen from the specified configuration file entry conf: UserConfig instance section [, option]: configuration entry [color]: default color [width]: default width [style]: default style """ if 'pen' not in option: option += '/pen' color = conf.get(section, option+"/color", color) color = QColor(color) width = conf.get(section, option+"/width", width) style_name = conf.get(section, option+"/style", style) style = getattr(Qt, style_name) return QPen(color, width, style)
def __init__(self, parent, ytitle="Y", yunit='', color=QColor( 255, 0, 0 )): self.curve = make.curve( [ ], [ ], '(Curve Name)', color ) self.dockwidget = myDockableWidget(parent, CurveWidget, toolbar=True ) # widget class: CurveWidget # plot class: CurvePlot # curve class: CurveItem self.plot = self.dockwidget.widget.plot self.plot.add_item( self.curve ) self.plot.set_antialiasing( True ) self.plot.set_axis_title( QwtPlot.xBottom, 'Time' ) self.plot.set_axis_unit( QwtPlot.xBottom, 's' ) self.plot.set_axis_title( QwtPlot.yLeft, ytitle ) self.plot.set_axis_unit( QwtPlot.yLeft, yunit ) self.plot.setAxisScaleDraw( QwtPlot.xBottom, DateTimeScaleDraw() ) #self.toolbar = QToolBar(_("Tools")) #self.curvewidget.widget.add_toolbar(self.toolbar, "default") #self.curvewidget.widget.register_tools() self.startIdx = 0 self.window_length = 60 # seconds
def update_axis_style(self, axis_id): """Update axis style""" axis_id = self.get_axis_id(axis_id) style = self.axes_styles[axis_id] title_font = style.title_font.build_font() ticks_font = style.ticks_font.build_font() self.setAxisFont(axis_id, ticks_font) if style.title and style.unit: title = "%s (%s)" % (style.title, style.unit) elif style.title: title = style.title else: title = style.unit axis_text = self.axisTitle(axis_id) axis_text.setFont(title_font) axis_text.setText(title) axis_text.setColor(QColor(style.color)) self.setAxisTitle(axis_id, axis_text) self.SIG_PLOT_LABELS_CHANGED.emit(self)
def _setup_colormap(cmap, cmdata): """Setup a QwtLinearColorMap according to matplotlib's data """ red = array(cmdata["red"]) green = array(cmdata["green"]) blue = array(cmdata["blue"]) qmin = QColor() qmin.setRgbF(red[0, 2], green[0, 2], blue[0, 2]) qmax = QColor() qmax.setRgbF(red[-1, 2], green[-1, 2], blue[-1, 2]) cmap.setColorInterval(qmin, qmax) indices = sorted(set(red[:, 0]) | set(green[:, 0]) | set(blue[:, 0])) for i in indices[1:-1]: idxr = red[:, 0].searchsorted(i) idxg = green[:, 0].searchsorted(i) idxb = blue[:, 0].searchsorted(i) compr = _interpolate(i, red[idxr - 1], red[idxr]) compg = _interpolate(i, green[idxg - 1], green[idxg]) compb = _interpolate(i, blue[idxb - 1], blue[idxb]) col = QColor() col.setRgbF(compr, compg, compb) cmap.addColorStop(i, col)
def fun(shape): shape.symbol.pen().setWidth(2) shape.symbol.setColor(QColor(255, 0, 0))
def __init__(self, parent): n = len(parent.sp) cmap = get_cmap('tab10', n * 2 + 3) self.colors = [ QPen(QColor(x[0] * 255, x[1] * 255, x[2] * 255), 1) for x in cmap.colors ] plots=\ [[ {'name':'Average Signal and Retrieved Signal','curves':[]}, {'name':'Residual Signal','curves':[]}], [ # {'name':'Averaging kernel for OEM retrieval','curves':['Averaging']}, {'name':'Measurement response to OEM retrieval','curves':[]}], [ {'name':'Altitude vs. H2O VMR','curves':['Prior']}], ] for i in range(n): plots[0][0]['curves'].append('Data' + str(i)) plots[0][0]['curves'].append('Retrieval' + str(i)) plots[0][1]['curves'].append('Residual' + str(i)) plots[1][0]['curves'].append('Response' + str(i)) plots[2][0]['curves'].append('OEM Retrieval' + str(i)) PlotPanel.__init__(self, parent=parent, plots=plots) #,axisLimits=axisLimits) self.colors[2 * n + 2].setWidth(3) self.curves['Prior'].setPen(self.colors[2 * n + 2]) for i in range(n): self.curves['OEM Retrieval' + str(i)].setPen(self.colors[2 * i]) self.curves['Data' + str(i)].setPen(self.colors[2 * i]) self.curves['Residual' + str(i)].setPen(self.colors[2 * i]) self.curves['Response' + str(i)].setPen(self.colors[2 * i]) self.colors[2 * i + 1].setWidth(3) self.curves['Retrieval' + str(i)].setPen(self.colors[2 * i + 1]) pDaRe = self.curves['Data' + str(i)].parent pResi = self.curves['Residual' + str(i)].parent # pAver=self.curves['Averaging'].parent pResp = self.curves['Response' + str(i)].parent pPOEM = self.curves['Prior'].parent pPOEM.set_titles(ylabel='Altitude [m]', xlabel='Retrieval') pDaRe.set_titles(ylabel='Brightness Temperature [K]', xlabel='Frequency [GHz]') pResi.set_titles(ylabel='Residual [K]', xlabel='Frequency [GHz]') # pAver.set_titles(ylabel='Altitude [m]',xlabel='') pResp.set_titles(ylabel='Altitude [m]', xlabel='') pDaRe.add_item(make.legend("TR")) pDaRe.setActive() pPOEM.add_item(make.legend("TR")) pPOEM.setActive() pDaRe.setDefaultAxis(axis=[142.1, 142.2, 100., 200.]) pResi.setDefaultAxis(axis=[142.1, 142.2, -.5, .5]) # pAver.setDefaultAxis(axis=[xmin,xmax,0.,1e5]) pResp.setDefaultAxis(axis=[-.1, 2., 0., 1e5]) pPOEM.setDefaultAxis(axis=[-.1, 12., 0., 1e5])