def data(self, modelIndex, role): if modelIndex.isValid: idx = modelIndex.row() else: return None if idx >= len(self.legendList): raise IndexError('list index out of range') item = self.legendList[idx] if role == qt.Qt.DisplayRole: # Data to be rendered in the form of text legend = QString(item[0]) #return QVariant(legend) return legend elif role == qt.Qt.SizeHintRole: #size = qt.QSize(200,50) print('LegendModel -- size hint role not implemented') return qt.QSize() elif role == qt.Qt.TextAlignmentRole: alignment = qt.Qt.AlignVCenter | qt.Qt.AlignLeft return alignment elif role == qt.Qt.BackgroundRole: # Background color, must be QBrush if idx % 2: brush = qt.QBrush(qt.QColor(240, 240, 240)) else: brush = qt.QBrush(qt.Qt.white) return brush elif role == qt.Qt.ForegroundRole: # ForegroundRole color, must be QBrush brush = qt.QBrush(qt.Qt.blue) return brush elif role == qt.Qt.CheckStateRole: return item[2] == True elif role == qt.Qt.ToolTipRole or role == qt.Qt.StatusTipRole: return '' elif role == self.iconColorRole: return item[1]['color'] elif role == self.iconLineWidthRole: return item[1]['linewidth'] elif role == self.iconSymbolRole: return item[1]['symbol'] elif role == self.showLineRole: return item[3] elif role == self.showSymbolRole: return item[4] elif role == self.legendTypeRole: return 0 # item[4] ..curveType.. #elif role == qt.Qt.EditRole: # return qt.QString('What now?') else: print('Unkown role requested: %s', str(role)) return None
def __setBrush(self): role = self.backgroundRole() palette = self.palette() if self.current and self.selected: self.brush = qt.QBrush(self.colors[1]) elif self.selected: self.brush = qt.QBrush(self.colors[0]) elif self.current: self.brush = qt.QBrush(self.colors[2]) else: self.brush = qt.QBrush() palette.setBrush(role, self.brush) self.update()
def paint(self, painter, rect, palette): painter.save() painter.setRenderHint(qt.QPainter.Antialiasing) # Scale painter to the icon height # current -> width = 2.5, height = 1.0 scale = float(self.height()) ratio = float(self.width()) / scale painter.scale(scale, scale) symbolOffset = qt.QPointF(.5 * (ratio - 1.), 0.) # Determine and scale offset offset = qt.QPointF( float(rect.left()) / scale, float(rect.top()) / scale) # Draw BG rectangle (for debugging) #bottomRight = qt.QPointF( # float(rect.right())/scale, # float(rect.bottom())/scale) #painter.fillRect(qt.QRectF(offset, bottomRight), # qt.QBrush(qt.Qt.green)) llist = [] if self.showLine: linePath = qt.QPainterPath() linePath.moveTo(0., 0.5) linePath.lineTo(ratio, 0.5) #linePath.lineTo(2.5,0.5) linePen = qt.QPen(qt.QBrush(self.lineColor), (self.lineWidth / self.height()), self.lineStyle, qt.Qt.FlatCap) llist.append((linePath, linePen, qt.QBrush(self.lineColor))) if self.showSymbol and len(self.symbol) and\ self.symbol not in ["None", " "]: # PITFALL ahead: Let this be a warning to others #symbolPath = Symbols[self.symbol] # Copy before translate! Dict is a mutable type symbolPath = qt.QPainterPath(Symbols[self.symbol]) symbolPath.translate(symbolOffset) symbolBrush = qt.QBrush(self.symbolColor, self.symbolStyle) symbolPen = qt.QPen( self.symbolOutlineBrush, # Brush 1. / self.height(), # Width qt.Qt.SolidLine # Style ) llist.append((symbolPath, symbolPen, symbolBrush)) # Draw for path, pen, brush in llist: path.translate(offset) painter.setPen(pen) painter.setBrush(brush) painter.drawPath(path) painter.restore()
def __init__(self, parent=None, scene=None, keepratio=True): if QTVERSION < '5.0': qt.QGraphicsRectItem.__init__(self, parent, scene) else: qt.QGraphicsRectItem.__init__(self, parent) #rect = parent.sceneBoundingRect() rect = parent.boundingRect() x = rect.x() y = rect.y() w = rect.width() h = rect.height() self._newRect = None self.keepRatio = keepratio self.setRect(qt.QRectF(x + w - 40, y + h - 40, 40, 40)) self.setAcceptHoverEvents(True) if DEBUG: self.setBrush(qt.QBrush(qt.Qt.white, qt.Qt.SolidPattern)) else: pen = qt.QPen() color = qt.QColor(qt.Qt.white) color.setAlpha(0) pen.setColor(color) pen.setStyle(qt.Qt.NoPen) self.setPen(pen) self.setBrush(color) self.setFlag(self.ItemIsMovable, True) self.show()
def __init__(self, parent, symbol, Z, name): qt.QPushButton.__init__(self, parent) self.symbol = symbol self.Z = Z self.name = name self.setText(symbol) self.setFlat(1) self.setCheckable(0) self.setSizePolicy( qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)) self.selected = 0 self.current = 0 self.colors = [ qt.QColor(qt.Qt.yellow), qt.QColor(qt.Qt.darkYellow), qt.QColor(qt.Qt.gray) ] self.brush = qt.QBrush() self.clicked.connect(self.clickedSlot)
def hoverEnterEvent(self, event): if self.parentItem().isSelected(): self.parentItem().setSelected(False) if self.keepRatio: self.setCursor(qt.QCursor(qt.Qt.SizeFDiagCursor)) else: self.setCursor(qt.QCursor(qt.Qt.SizeAllCursor)) self.setBrush(qt.QBrush(qt.Qt.yellow, qt.Qt.SolidPattern)) return qt.QGraphicsRectItem.hoverEnterEvent(self, event)
def setSelected(self, b): self.selected = b if b: role = self.backgroundRole() palette = self.palette() palette.setBrush(role, self.brush) self.setPalette(palette) else: role = self.backgroundRole() palette = self.palette() palette.setBrush(role, qt.QBrush()) self.setPalette(palette) self.update()
def __init__(self, parent, peak): qt.QPushButton.__init__(self, parent) #, peak) self.peak = peak font = self.font() font.setBold(1) self.setText(peak) self.setFlat(1) if QTVERSION < '4.0.0': self.setToggleButton(0) self.setSizePolicy( qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)) self.selected = 0 self.brush = qt.QBrush(qt.QColor(qt.Qt.yellow)) self.clicked.connect(self.clickedSlot)
def __init__(self, parent=None): super(LegendIcon, self).__init__(parent) # Visibilities self.showLine = True self.showSymbol = True # Line attributes self.lineStyle = qt.Qt.SolidLine self.lineWidth = 1. self.lineColor = qt.Qt.green self.symbol = '' # Symbol attributes self.symbolStyle = qt.Qt.SolidPattern self.symbolColor = qt.Qt.green self.symbolOutlineBrush = qt.QBrush(qt.Qt.white) # Control widget size: sizeHint "is the only acceptable # alternative, so the widget can never grow or shrink" # (c.f. Qt Doc, enum QSizePolicy::Policy) self.setSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Fixed)
class RadarView(qt.QGraphicsView): """Widget presenting a synthetic view of a 2D area and the current visible area. Coordinates are as in QGraphicsView: x goes from left to right and y goes from top to bottom. This widget preserves the aspect ratio of the areas. The 2D area and the visible area can be set with :meth:`setDataRect` and :meth:`setVisibleRect`. When the visible area has been dragged by the user, its new position is signaled by the *visibleRectDragged* signal. It is possible to invert the direction of the axes by using the :meth:`scale` method of QGraphicsView. """ visibleRectDragged = qt.pyqtSignal(float, float, float, float) """Signals that the visible rectangle has been dragged. It provides: left, top, width, height in data coordinates. """ _DATA_PEN = qt.QPen(qt.QColor('white')) _DATA_BRUSH = qt.QBrush(qt.QColor('light gray')) _VISIBLE_PEN = qt.QPen(qt.QColor('red')) _VISIBLE_BRUSH = qt.QBrush(qt.QColor(0, 0, 0, 0)) _TOOLTIP = 'Radar View:\nVisible area (in red)\nof the image (in gray).' _PIXMAP_SIZE = 256 class _DraggableRectItem(qt.QGraphicsRectItem): """RectItem which signals its change through visibleRectDragged.""" def __init__(self, *args, **kwargs): super(RadarView._DraggableRectItem, self).__init__(*args, **kwargs) self.setFlag(qt.QGraphicsItem.ItemIsMovable) self.setFlag(qt.QGraphicsItem.ItemSendsGeometryChanges) self._ignoreChange = False self._constraint = 0, 0, 0, 0 def setConstraintRect(self, left, top, width, height): """Set the constraint rectangle for dragging. The coordinates are in the _DraggableRectItem coordinate system. This constraint only applies to modification through interaction (i.e., this constraint is not applied to change through API). If the _DraggableRectItem is smaller than the constraint rectangle, the _DraggableRectItem remains within the constraint rectangle. If the _DraggableRectItem is wider than the constraint rectangle, the constraint rectangle remains within the _DraggableRectItem. """ self._constraint = left, left + width, top, top + height def setPos(self, *args, **kwargs): """Overridden to ignore changes from API in itemChange.""" self._ignoreChange = True super(RadarView._DraggableRectItem, self).setPos(*args, **kwargs) self._ignoreChange = False def moveBy(self, *args, **kwargs): """Overridden to ignore changes from API in itemChange.""" self._ignoreChange = True super(RadarView._DraggableRectItem, self).moveBy(*args, **kwargs) self._ignoreChange = False def itemChange(self, change, value): """Callback called before applying changes to the item.""" if (change == qt.QGraphicsItem.ItemPositionChange and not self._ignoreChange): # Makes sure that the visible area is in the data # or that data is in the visible area if area is too wide x, y = value.x(), value.y() xMin, xMax, yMin, yMax = self._constraint if self.rect().width() <= (xMax - xMin): if x < xMin: value.setX(xMin) elif x > xMax - self.rect().width(): value.setX(xMax - self.rect().width()) else: if x > xMin: value.setX(xMin) elif x < xMax - self.rect().width(): value.setX(xMax - self.rect().width()) if self.rect().height() <= (yMax - yMin): if y < yMin: value.setY(yMin) elif y > yMax - self.rect().height(): value.setY(yMax - self.rect().height()) else: if y > yMin: value.setY(yMin) elif y < yMax - self.rect().height(): value.setY(yMax - self.rect().height()) if self.pos() != value: # Notify change through signal views = self.scene().views() assert len(views) == 1 views[0].visibleRectDragged.emit( value.x() + self.rect().left(), value.y() + self.rect().top(), self.rect().width(), self.rect().height()) return value return super(RadarView._DraggableRectItem, self).itemChange(change, value) def __init__(self, parent=None): self._scene = qt.QGraphicsScene() self._dataRect = self._scene.addRect(0, 0, 1, 1, self._DATA_PEN, self._DATA_BRUSH) self._visibleRect = self._DraggableRectItem(0, 0, 1, 1) self._visibleRect.setPen(self._VISIBLE_PEN) self._visibleRect.setBrush(self._VISIBLE_BRUSH) self._scene.addItem(self._visibleRect) super(RadarView, self).__init__(self._scene, parent) self.setHorizontalScrollBarPolicy(qt.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(qt.Qt.ScrollBarAlwaysOff) self.setFocusPolicy(qt.Qt.NoFocus) self.setStyleSheet('border: 0px') self.setToolTip(self._TOOLTIP) def sizeHint(self): # """Overridden to avoid sizeHint to depend on content size.""" return self.minimumSizeHint() def wheelEvent(self, event): # """Overridden to disable vertical scrolling with wheel.""" event.ignore() def resizeEvent(self, event): # """Overridden to fit current content to new size.""" self.fitInView(self._scene.itemsBoundingRect(), qt.Qt.KeepAspectRatio) super(RadarView, self).resizeEvent(event) def setDataRect(self, left, top, width, height): """Set the bounds of the data rectangular area. This sets the coordinate system. """ self._dataRect.setRect(left, top, width, height) self._visibleRect.setConstraintRect(left, top, width, height) self.fitInView(self._scene.itemsBoundingRect(), qt.Qt.KeepAspectRatio) def setVisibleRect(self, left, top, width, height): """Set the visible rectangular area. The coordinates are relative to the data rect. """ self._visibleRect.setRect(0, 0, width, height) self._visibleRect.setPos(left, top) self.fitInView(self._scene.itemsBoundingRect(), qt.Qt.KeepAspectRatio)
def fillfrommca(self, mcaresult, diag=1): line0 = 0 region = 0 alreadyforced = 0 for result in mcaresult: region = region + 1 if result['chisq'] is not None: chisq = QString("%6.2f" % (result['chisq'])) else: chisq = QString("Fit Error") if 1: xbegin = QString("%6g" % (result['xbegin'])) xend = QString("%6g" % (result['xend'])) fitlabel, fitpars, fitsigmas = self.__getfitpar(result) if QTVERSION < '4.0.0': qt.QHeader.setLabel(self.horizontalHeader(), 1, "Fit " + fitlabel) else: item = self.horizontalHeaderItem(1) item.setText("Fit " + fitlabel) i = 0 for (pos, area, sigma, fwhm) in result['mca_areas']: line0 = line0 + 1 if QTVERSION < '4.0.0': nlines = self.numRows() if (line0 > nlines): self.setNumRows(line0) else: nlines = self.rowCount() if (line0 > nlines): self.setRowCount(line0) line = line0 - 1 #pos=QString(str(pos)) #area=QString(str(area)) #sigma=QString(str(sigma)) #fwhm=QString(str(fwhm)) tregion = QString(str(region)) pos = QString("%6g" % (pos)) fitpar = QString("%6g" % (fitpars[i])) if fitlabel == 'Area': sigma = max(sigma, fitsigmas[i]) areastr = QString("%6g" % (area)) sigmastr = QString("%6.3g" % (sigma)) fwhm = QString("%6g" % (fwhm)) tregion = QString("%6g" % (region)) fields = [ pos, fitpar, areastr, sigmastr, fwhm, chisq, tregion, xbegin, xend ] col = 0 recolor = 0 if fitlabel == 'Area': if diag: if abs(fitpars[i] - area) > (3.0 * sigma): color = qt.QColor(255, 182, 193) recolor = 1 for field in fields: key = self.item(line, col) if key is None: key = qt.QTableWidgetItem(field) self.setItem(line, col, key) else: item.setText(field) if recolor: #function introduced in Qt 4.2.0 if QTVERSION >= '4.2.0': item.setBackground(qt.QBrush(color)) item.setFlags(qt.Qt.ItemIsSelectable | qt.Qt.ItemIsEnabled) col = col + 1 if recolor: if not alreadyforced: alreadyforced = 1 self.scrollToItem(self.item(line, 0)) i += 1 i = 0 for label in self.labels: self.resizeColumnToContents(i) i = i + 1 ndict = {} ndict['event'] = 'McaTableFilled' self.sigMcaTableSignal.emit(ndict)