def drawBorder(pixmap): painter = qt.QPainter(pixmap) rect = pixmap.rect() tl = rect.topLeft() tr = rect.topRight() bl = rect.bottomLeft() br = rect.bottomRight() for start, end in [[tl, tr], [tr, br], [br, bl], [bl, tl]]: painter.drawLine(start, end)
def __print(self): """ send all items of the canvas to the printer (file or device) """ prt = qt.QPainter() prt.begin(self.printer) for item in self.canvasView.getPrintItems(): item.printTo(prt) prt.end() self.accept()
def timeimage(self, request=''): """ For timing and debugging - return an image with the current time rendered as text down to the hundredth of a second :param color: hex encoded RGB of dashed border (default 333 for dark gray) :return: png image """ # check arguments p = urllib.parse.urlparse(request.decode()) q = urllib.parse.parse_qs(p.query) try: color = "#" + q['color'][0].strip().lower() except KeyError: color = "#330" # # make a generally transparent image, # imageWidth = 128 imageHeight = 32 timeImage = qt.QImage(imageWidth, imageHeight, qt.QImage().Format_ARGB32) timeImage.fill(0) # a painter to use for various jobs painter = qt.QPainter() # draw a border around the pixmap painter.begin(timeImage) pen = qt.QPen() color = qt.QColor(color) color.setAlphaF(0.8) pen.setColor(color) pen.setWidth(5) pen.setStyle(3) # dotted line (Qt::DotLine) painter.setPen(pen) rect = qt.QRect(1, 1, imageWidth - 2, imageHeight - 2) painter.drawRect(rect) color = qt.QColor("#333") pen.setColor(color) painter.setPen(pen) position = qt.QPoint(10, 20) text = str(time.time()) # text to draw painter.drawText(position, text) painter.end() # convert the image to vtk, then to png from there vtkTimeImage = vtk.vtkImageData() slicer.qMRMLUtils().qImageToVtkImageData(timeImage, vtkTimeImage) pngData = self.vtkImageDataToPNG(vtkTimeImage) return pngData, b'image/png'
def draw(self, p): """ """ if self.fullRedrawFlag: scale = float(self.width())/self.imageWidth wm = p.worldMatrix() nwm = qt.QWMatrix(wm.m11(),wm.m12(),wm.m21(),wm.m22(),wm.dx(),wm.dy()) nwm = nwm.scale(scale, scale) np = qt.QPainter(p.device()) np.setWorldMatrix(nwm) np.drawPixmap(int(self.x()/scale)+1, int(self.y()/scale)+1, \ self.pixmap) PrintCanvasRectangle.draw(self, p)
def paintEvent(self, event): p = qt.QPainter() p.begin(self) n = int(math.sqrt(self.nccds)) w = self.width() h = self.height() step_x = w / n step_y = h / n #logging.getLogger().info("%s", self.temp_list) for i in range(n): x = step_x * i y = step_y * i for j in range(n): t = self.temp_list[j * 3 + i] if t is None: c_b = 255 c_g = 255 c_r = 255 else: #logging.getLogger().info("%d", j*3+i) c_b = 255 - int((255 / 40.0) * t + 255) if c_b > 255: c_b = 255 elif c_b < 0: c_b = 0 c_g = int((255 / 40.0) * t + 255) if c_g > 255: c_g = 0 elif c_g < 0: c_g = 0 if c_g > 0 and c_b > 0: c_r = 0 else: c_r = 255 - c_b c = qt.QColor(c_r, c_g, c_b) brush = qt.QBrush(c) p.fillRect(x + 1, j * step_y + 1, x + step_x - 1, (j + 1) * step_y - 1, brush) p.setPen(qt.QPen(qt.QColor(0, 0, 0))) #logging.getLogger().info("%d %d", x, y) p.drawLine(x, 0, x, h) p.drawLine(0, y, w, y) p.end() return qt.QWidget.paintEvent(self, event)
def __init__(self, parent=None, width=400, height=400, showWidget=False, scale=False): super(LayerReveal, self).__init__() self.width = width self.height = height self.showWidget = showWidget self.scale = scale self.renderer = None # utility Qt instances for use in methods self.gray = qt.QColor() self.gray.setRedF(0.5) self.gray.setGreenF(0.5) self.gray.setBlueF(0.5) # a painter to use for various jobs self.painter = qt.QPainter() # make a qwidget display if self.showWidget: self.frame = qt.QFrame(parent) mw = slicer.util.mainWindow() self.frame.setGeometry(mw.x, mw.y, self.width, self.height) self.frameLayout = qt.QVBoxLayout(self.frame) self.label = qt.QLabel() self.frameLayout.addWidget(self.label) self.frame.show() # make an image actor in the slice view self.vtkImage = vtk.vtkImageData() self.mrmlUtils = slicer.qMRMLUtils() self.imageMapper = vtk.vtkImageMapper() self.imageMapper.SetColorLevel(128) self.imageMapper.SetColorWindow(255) if vtk.VTK_MAJOR_VERSION <= 5: self.imageMapper.SetInput(self.vtkImage) else: self.imageMapper.SetInputData(self.vtkImage) self.actor2D = vtk.vtkActor2D() self.actor2D.SetMapper(self.imageMapper)
def get_qimage(self, image, canvas, zoom=1): """ Gets the QImage from a parent widget. :param image: The QWidget that contains the image to extract :type image: QWidget :param canvas: The QCanvas obejct to add as overlay :type canvas: QCanvas :param zoom: Zoom level :type zoom: int. :returns: The QImage contained in the parent widget. :rtype: QImage """ if canvas is not None and image is not None: device = qt.QPixmap(image) painter = qt.QPainter(device) zoom = 1.0 / zoom painter.setWorldMatrix(qt.QWMatrix(zoom, 0, 0, zoom, 0, 0)) if isinstance(canvas, list): itemsList = canvas else: itemsList = canvas.allItems() for item in itemsList: if item.isVisible(): if hasattr(item, 'setScrollView'): #remove standalone items continue item.draw(painter) painter.end() img = device.convertToImage() else: img = image return img
def __init__(self, parent=None): self.nameSize = 24 self.CrosshairNode = None self.CrosshairNodeObserverTag = None self.frame = qt.QFrame(parent) self.frame.setLayout(qt.QVBoxLayout()) # Set horizontal policy to Ignored to prevent a long segment or volume name making the widget wider. # If the module panel made larger then the image viewers would move and the mouse pointer position # would change in the image, potentially pointing outside the node with the long name, resulting in the # module panel collapsing to the original size, causing an infinite oscillation. qSize = qt.QSizePolicy() qSize.setHorizontalPolicy(qt.QSizePolicy.Ignored) qSize.setVerticalPolicy(qt.QSizePolicy.Preferred) self.frame.setSizePolicy(qSize) modulePath = slicer.modules.dataprobe.path.replace("DataProbe.py", "") self.iconsDIR = modulePath + '/Resources/Icons' self.showImage = False # Used in _createMagnifiedPixmap() self.imageCrop = vtk.vtkExtractVOI() self.canvas = vtk.vtkImageCanvasSource2D() self.painter = qt.QPainter() self.pen = qt.QPen() self._createSmall() # Helper class to calculate and display tensor scalars self.calculateTensorScalars = CalculateTensorScalars() # Observe the crosshair node to get the current cursor position self.CrosshairNode = slicer.mrmlScene.GetFirstNodeByClass( 'vtkMRMLCrosshairNode') if self.CrosshairNode: self.CrosshairNodeObserverTag = self.CrosshairNode.AddObserver( slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, self.processEvent)
def paintEvent(self, event): qt.QFrame.paintEvent(self, event) if self.executionMode: return p = qt.QPainter(self) p.setPen(qt.QPen(qt.Qt.black, 3)) if self.orientation == 'horizontal': h = self.height() / 2 p.drawLine(0, h, self.width(), h) p.drawLine(0, h, 5, h - 5) p.drawLine(0, h, 5, h + 5) p.drawLine(self.width(), h, self.width() - 5, h - 5) p.drawLine(self.width(), h, self.width() - 5, h + 5) else: w = self.width() / 2 p.drawLine(self.width() / 2, 0, self.width() / 2, self.height()) p.drawLine(w, 0, w - 5, 5) p.drawLine(w, 0, w + 5, 5) p.drawLine(w, self.height(), w - 5, self.height() - 5) p.drawLine(w, self.height(), w + 5, self.height() - 5)
def __init__(self, parent=None,type='small'): self.type = type self.nameSize = 24 # the currentLayoutName is tag on the slice node that corresponds # view which should currently be shown in the DataProbe window. # Keeping track of this allows us to respond to non-interactor updates # to the slice (like from an external tracker) but only in the view where # the mouse has most recently entered. self.currentLayoutName = None self.CrosshairNode = None self.CrosshairNodeObserverTag = None self.frame = qt.QFrame(parent) self.frame.setLayout(qt.QVBoxLayout()) modulePath = slicer.modules.dataprobe.path.replace("DataProbe.py","") self.iconsDIR = modulePath + '/Resources/Icons' self.imageCrop = vtk.vtkExtractVOI() self.imageZoom = 10 self.showImage = False self.painter = qt.QPainter() self.pen = qt.QPen() if type == 'small': self.createSmall() #Helper class to calculate and display tensor scalars self.calculateTensorScalars = CalculateTensorScalars() # Observe the crosshair node to get the current cursor position self.CrosshairNode = slicer.mrmlScene.GetNthNodeByClass(0, 'vtkMRMLCrosshairNode') if self.CrosshairNode: self.CrosshairNodeObserverTag = self.CrosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, self.processEvent)
def editMarkups(self, selectOption, fiducialsNode, curveNode, viewNode): layoutManager = slicer.app.layoutManager() threeDWidget = layoutManager.viewWidget(viewNode) threeDView = threeDWidget.threeDView() aspectRatio = threeDWidget.width / threeDWidget.height className = "vtkMRMLMarkupsDisplayableManager" markupsDisplayableManager = threeDView.displayableManagerByClassName( className) fiducialsWidget = markupsDisplayableManager.GetWidget( fiducialsNode.GetDisplayNode()) fiducialsRepresentation = fiducialsWidget.GetRepresentation() cameraNode = slicer.modules.cameras.logic().GetViewActiveCameraNode( viewNode) camera = cameraNode.GetCamera() raswToXYZW = vtk.vtkMatrix4x4() modelView = camera.GetModelViewTransformMatrix() projection = camera.GetProjectionTransformMatrix( aspectRatio, 1, 100) # near/far are arbitrary raswToXYZW.Multiply4x4(projection, modelView, raswToXYZW) def rasToColumnRow(ras): rasw = *ras, 1 xyzw = raswToXYZW.MultiplyPoint(rasw) x, y = [xyzw[0], xyzw[1]] if viewNode.GetRenderMode() == viewNode.Perspective: x, y = [x / xyzw[3], y / xyzw[3]] column = (x + 1) / 2 * threeDWidget.width row = (1 - (y + 1) / 2) * threeDWidget.height return column, row selectionPolygon = qt.QPolygonF() for index in range(curveNode.GetNumberOfControlPoints()): ras = [0] * 3 curveNode.GetNthControlPointPositionWorld(index, ras) column, row = rasToColumnRow(ras) point = qt.QPointF(column, row) selectionPolygon.push_back(point) pickImage = qt.QImage(threeDWidget.width, threeDWidget.height, qt.QImage().Format_ARGB32) backgroundColor = qt.QColor("#ffffffff") pickImage.fill(backgroundColor) painter = qt.QPainter() painter.begin(pickImage) painterPath = qt.QPainterPath() painterPath.addPolygon(selectionPolygon) brush = qt.QBrush(qt.Qt.SolidPattern) painter.setBrush(brush) painter.drawPath(painterPath) painter.end() debugging = False if debugging: pixmap = qt.QPixmap().fromImage(pickImage) slicer.modules.label = qt.QLabel() slicer.modules.label.setPixmap(pixmap) slicer.modules.label.show() visibleCount = 0 pickedCount = 0 for index in range(fiducialsNode.GetNumberOfControlPoints()): pointVisible = fiducialsRepresentation.GetNthControlPointViewVisibility( index) if pointVisible: visibleCount += 1 ras = [0] * 3 fiducialsNode.GetNthControlPointPositionWorld(index, ras) column, row = rasToColumnRow(ras) if (column >= 0 and column < pickImage.width and row >= 0 and row < pickImage.height): pickColor = pickImage.pixelColor(column, row) picked = (pickColor != backgroundColor) if picked: pickedCount += 1 if selectOption == "set": if pointVisible: fiducialsNode.SetNthControlPointSelected(index, picked) else: fiducialsNode.SetNthControlPointSelected(index, False) elif selectOption == "add": if picked and pointVisible: fiducialsNode.SetNthControlPointSelected(index, True) elif selectOption == "unset": if picked and pointVisible: fiducialsNode.SetNthControlPointSelected(index, False) else: logging.error(f"Unknown selectOption {selectOption}")
def onListSelected(self): item = self.list.selectedItem() pixmap = None if item is None: pass elif item == self.root: pass else: element = self.device.getComponentByAddress(item.text(0)) if element is not None: if element.isLeaf(): img_str = element.fetchImage() if img_str is not None: pixmap = qt.QPixmap() pixmap.loadFromData(img_str) if self.inversed_image: m = qt.QWMatrix() m.scale(1.0, -1.0) pixmap = pixmap.xForm(m) x = element.getImageX() y = element.getImageY() if (x is not None) and (y is not None): # Overlays p = qt.QPainter() p.begin(pixmap) p.setPen(qt.QPen(qt.QColor(0xE0, 0xE0, 0), 2)) size = 8 center = qt.QPoint( int(x / 100.0 * pixmap.width()), int(y / 100.0 * pixmap.height()), ) if self.inversed_image: center.setY( int((100.0 - y) / 100.0 * pixmap.height())) p.drawLine( qt.QPoint(center.x(), center.y() - size), qt.QPoint(center.x(), center.y() + size), ) p.drawLine( qt.QPoint(center.x() - size, center.y()), qt.QPoint(center.x() + size, center.y()), ) p.setPen(qt.QPen(qt.QColor(0, 0xC0, 0), 2)) size = 20 center = qt.QPoint( int(x / 100.0 * pixmap.width()), int(y / 100.0 * pixmap.height()), ) if self.inversed_image: center.setY( int((100.0 - y) / 100.0 * pixmap.height())) p.drawLine( qt.QPoint(center.x(), center.y() - size), qt.QPoint(center.x(), center.y() + size), ) p.drawLine( qt.QPoint(center.x() - size, center.y()), qt.QPoint(center.x() + size, center.y()), ) p.end() self.widget.lbImage.setPixmap(pixmap) # This check because don't know how to clear QLabel but assigniong an empty pixmap, what prints a warning message # if pixmap!=self._empty_image_pixmap or self.widget.lbImage.pixmap() is None or self.widget.lbImage.pixmap().width()>0: # self.widget.lbImage.setPixmap(pixmap) # self.widget.lbImage.setVisible(pixmap != self._empty_image_pixmap) if pixmap is not None: self.widget.lbImage.setPixmap(pixmap) self.widget.lbImage.show() else: self.widget.lbImage.clear() self.widget.lbImage.hide()
def paintEvent(self, event=None): qp = qt.QPainter() qp.begin(self) w = self.width h = self.height mid_x = w / 2 qp.setPen(self.pen_fg_base_frame) qp.drawRect(self.margin_x, self.margin_y, w / 2 - self.margin_x - self.inner_margin_x, self.connector_box_h) qp.drawRect(mid_x + self.inner_margin_x, self.margin_y, w / 2 - self.margin_x - self.inner_margin_x, self.connector_box_h) if len(self.connectors) >= 2: qp.setPen(self.pen_fg_base) qp.drawText(self.margin_x + self.inner_margin_x, self.connector_text_y, self.connectors[0].cname + ' :') qp.drawText(mid_x + self.inner_margin_x * 2, self.connector_text_y, self.connectors[1].cname + ' :') text_x = [self.connector0_text_x, self.connector1_text_x + mid_x] for i in range(2): if self.connectors[i].active(): if self.connectors[i].connected(): qp.setPen(self.pen_fg_act) qp.drawText(text_x[i], self.connector_text_y, "Connected") else: qp.setPen(self.pen_fg_on) qp.drawText(text_x[i], self.connector_text_y, "Waiting") else: qp.setPen(self.pen_fg_off) qp.drawText(text_x[i], self.connector_text_y, "Off") # Draw LEDs if self.catheters: n = self.catheters.getNumberOfCatheters() for i in range(n): cath = self.catheters.getCatheter(i) if cath: if cath.isActive(): qp.setPen(self.pen_fg_act) else: qp.setPen(self.pen_fg_base) text_y = self.catheter_base_y + self.catheter_row_h * i + self.font_h qp.drawText(self.margin_x + self.inner_margin_x, text_y, cath.name + ' :') # Coil activation for j in range(8): c_id = j if not cath.coilOrder: # Proximal -> Distal c_id = 7 - j if cath.activeCoils[c_id]: qp.setPen(self.pen_led_on) else: qp.setPen(self.pen_led_off) x = self.catheter_base_x + self.led_intv_x * j qp.drawEllipse( qt.QPoint( x + self.font_w / 2, self.catheter_base_y + self.catheter_row_h * i + self.font_h / 2), self.led_r_w, self.led_r_h) qp.drawText(x, text_y, str(c_id + 1)) qp.end()
def __init__(self, parent=None, width=400, height=400, showWidget=False, scale=False): super(ROIManager, self).__init__() self.width = width self.height = height self.showWidget = showWidget self.scale = scale self.renderer = None self.ROIRadius = 20.0 self.minValueBG = 0 self.maxValueBG = 0 self.minValueFG = 0 self.maxValueFG = 0 self.probeWidget = None self.drawOverlay = 0 # utility Qt instances for use in methods self.gray = qt.QColor() self.gray.setRedF(0.5) self.gray.setGreenF(0.5) self.gray.setBlueF(0.5) # a painter to use for various jobs self.painter = qt.QPainter() # make a qwidget display if self.showWidget: self.frame = qt.QFrame(parent) mw = slicer.util.mainWindow() self.frame.setGeometry(mw.x, mw.y, self.width, self.height) self.frameLayout = qt.QVBoxLayout(self.frame) self.label = qt.QLabel() self.frameLayout.addWidget(self.label) self.frame.show() # make an image actor in the slice view self.vtkImage = vtk.vtkImageData() self.mrmlUtils = slicer.qMRMLUtils() self.imageMapper = vtk.vtkImageMapper() self.imageMapper.SetColorLevel(128) self.imageMapper.SetColorWindow(255) if vtk.VTK_MAJOR_VERSION <= 5: self.imageMapper.SetInput(self.vtkImage) else: self.imageMapper.SetInputData(self.vtkImage) self.actor2D = vtk.vtkActor2D() self.actor2D.SetMapper(self.imageMapper) # make a circle actor self.circle = vtk.vtkRegularPolygonSource() self.circle.SetNumberOfSides(50) self.circle.SetRadius(5) self.circle.SetCenter(0, 0, 0) self.circle.GeneratePolylineOn() self.circle.GeneratePolygonOff() self.circle.Update() self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() if vtk.VTK_MAJOR_VERSION <= 5: self.mapper.SetInput(self.circle.GetOutput()) else: self.mapper.SetInputConnection(self.circle.GetOutputPort()) self.actor.SetMapper(self.mapper) property_ = self.actor.GetProperty() property_.SetColor(1, 1, 0) property_.SetLineWidth(1)
def paintEvent(self, event): Qt.QFrame.paintEvent(self, event) painter = Qt.QPainter(self) painter.setClipRect(self.contentsRect()) self.drawContents(painter)