def ejecutar(self): """accion correspondiente a la pulsacion del boton """ #Carregar layers de districtes i barris zones = ["districtes", "barris"] for zona in zones: pathBoxes = "Dades\\Zones.gpkg|layername=" + zona layerBoxes = QgsVectorLayer(pathBoxes, 'ogr') if not layerBoxes.isValid(): print ("Layer failed to load!") vlayer = QgsProject.instance().mapLayers().values() #Propietats imatge del mapeta settings = QgsMapSettings() # settings.setLayers(vlayer) settings.setLayers(self.canvas.layers()) settings.setBackgroundColor(QColor(255, 255, 255)) settings.setOutputSize(QSize(self.lado, self.lado)) features = layerBoxes.getFeatures() kk = layerBoxes.featureCount() nn=0 for feature in features: # if zona=='districtes' and feature[1] != '10': # continue # if zona=='barris' and ( feature[3] != '10' ): # continue # if zona=='barris' : # continue # pretendo: toda la geometria a una convex hull geoHull= feature.geometry().convexHull() polHull= geoHull.asPolygon() try: for ring in polHull: convexHull=[] for v in ring: xx=(v.x()); yy=(v.y()) pnt=QPointF(xx,yy) convexHull.append(pnt) except Exception as ee: print(str(ee)) centro,radio= FindMinimalBoundingCircle(convexHull) nn+=1 print("zona:{} nº {} centro: {},{} radio:{}" \ .format(zona,nn,round(centro.x(),3),round(centro.y(),3),round(radio,3))) # print("zona:{zona} nº {nn} centro: {centro.x()}{centro.y()} radio{radio}") nom = feature[2] if nom == "Les Corts" or nom == "les Corts": a = "a" x1 = centro.x() + radio #xmax x2 = centro.x() - radio #xmin y1 = centro.y() + radio #ymax y2 = centro.y() - radio #xmin settings.setExtent(QgsRectangle(x2,y2,x1,y1)) ira= settings.hasValidSettings() if ira==False: print("mal") render = QgsMapRendererSequentialJob(settings) # #Renderitzar imatge PNG render.start() render.waitForFinished() errors= render.errors() img = render.renderedImage() img = img.convertToFormat(QImage.Format_ARGB32) # Preparació per convertir img quadrada a out_img circular out_img = QImage(img.width(), img.width(), QImage.Format_ARGB32) out_img.fill(Qt.transparent) # #Pinzell i pintar imatge brush = QBrush(img) painter = QPainter(out_img) painter.setBrush(brush) pen= QPen(self.color, 1, Qt.SolidLine) #qVista claro # pen= QPen(self.parent.color, 1, Qt.SolidLine) #qVista claro painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing, True) painter.drawEllipse(0, 0, img.width(), img.width()) painter.end() # #Guardar imatge scaled_pixmap = QPixmap.fromImage(out_img) # scaled_pixmap = QPixmap.fromImage(img) image_location = os.path.join("Imatges\\capturesMapeta\\", nom + "_" + zona[0] + ".png") scaled_pixmap.save(image_location, "png") ##Crear arxiu de metadades PGW #Nom fitzer PGW split_nombre=os.path.splitext(image_location) filenamePgw = split_nombre[0] + ".pgw" wld = open(filenamePgw, "w") # #Rang mapeta xdist = x1 - x2 ydist = y1 - y2 iheight = self.lado #tamany imatge iwidth = self.lado xmin = x2 ymin = y2 # #Escriure PGW wld.writelines("%s\n" % (xdist/iwidth)) wld.writelines("0.0\n") wld.writelines("0.0\n") wld.writelines("%s\n" % (ydist/iheight)) wld.writelines("%s\n" % xmin) wld.writelines("%s\n" % ymin) wld.close
def paint(self, painter, option, widget): self.stabilize() if self.m_sticks: painter.setPen(Qt.white) for n1, n2 in Bones: node1 = self.m_nodes[n1] node2 = self.m_nodes[n2] painter.drawLine(node1.pos(), node2.pos()) else: # First bone is neck and will be used for head. path = QPainterPath() path.moveTo(self.posFor(0)) path.lineTo(self.posFor(1)) # Right arm. path.lineTo(self.posFor(2)) path.lineTo(self.posFor(6)) path.lineTo(self.posFor(7)) # Left arm. path.moveTo(self.posFor(3)) path.lineTo(self.posFor(8)) path.lineTo(self.posFor(9)) # Body. path.moveTo(self.posFor(2)) path.lineTo(self.posFor(4)) path.lineTo(self.posFor(10)) path.lineTo(self.posFor(11)) path.lineTo(self.posFor(5)) path.lineTo(self.posFor(3)) path.lineTo(self.posFor(1)) # Right leg. path.moveTo(self.posFor(10)) path.lineTo(self.posFor(12)) path.lineTo(self.posFor(13)) # Left leg. path.moveTo(self.posFor(11)) path.lineTo(self.posFor(14)) path.lineTo(self.posFor(15)) painter.setPen( QPen(self.m_penColor, 5.0, Qt.SolidLine, Qt.RoundCap)) painter.draw_path(path) n1, n2 = Bones[0] node1 = self.m_nodes[n1] node2 = self.m_nodes[n2] dist = node2.pos() - node1.pos() sinAngle = dist.x() / math.hypot(dist.x(), dist.y()) angle = math.degrees(math.asin(sinAngle)) headPos = node1.pos() painter.translate(headPos) painter.rotate(-angle) painter.setBrush(self.m_fillColor) painter.drawEllipse(QPointF(0, 0), 50.0, 50.0) painter.setBrush(self.m_penColor) painter.setPen( QPen(self.m_penColor, 2.5, Qt.SolidLine, Qt.RoundCap)) # Eyes. if self.m_isDead: painter.drawLine(-30.0, -30.0, -20.0, -20.0) painter.drawLine(-20.0, -30.0, -30.0, -20.0) painter.drawLine(20.0, -30.0, 30.0, -20.0) painter.drawLine(30.0, -30.0, 20.0, -20.0) else: painter.drawChord(QRectF(-30.0, -30.0, 25.0, 70.0), 30.0 * 16, 120.0 * 16) painter.drawChord(QRectF(5.0, -30.0, 25.0, 70.0), 30.0 * 16, 120.0 * 16) # Mouth. if self.m_isDead: painter.drawLine(-28.0, 2.0, 29.0, 2.0) else: painter.setBrush(QColor(128, 0, 64)) painter.drawChord(QRectF(-28.0, 2.0 - 55.0 / 2.0, 57.0, 55.0), 0.0, -180.0 * 16) # Pupils. if not self.m_isDead: painter.setPen( QPen(self.m_fillColor, 1.0, Qt.SolidLine, Qt.RoundCap)) painter.setBrush(self.m_fillColor) painter.drawEllipse(QPointF(-12.0, -25.0), 5.0, 5.0) painter.drawEllipse(QPointF(22.0, -25.0), 5.0, 5.0)
def draw_circle(self, qp, circle): qp.setPen( QPen(QColor(randint(0, 255), randint(0, 255), randint(0, 255)), 4)) x, y, r = circle qp.drawEllipse(x - r // 2, y - r // 2, r, r)
def add_land_mark(self, x, y): pen = QPen(QColor(100, 200, 0), 0.5, Qt.SolidLine, Qt.RoundCap)
def draw_line(self, start, end, color=QColor(0, 0, 100)): cone_pen = QPen(color, 2, Qt.DashLine, Qt.RoundCap) start = self.get_px_pos_from_m(start) end = self.get_px_pos_from_m(end) self.addLine(start[0], start[1], end[0], end[1], cone_pen)
path.moveTo(i, close[i]) path.lineTo(i + 1, close[i + 1]) path2 = QPainterPath() for i in range(close2.size - 1): path2.moveTo(i, close2[i]) path2.lineTo(i + 1, close2[i + 1]) app = QApplication([]) view = MyView() scene = QGraphicsScene() path_item = QGraphicsPathItem(path) pen = QPen(Qt.darkGray) pen.setCosmetic(True) path_item.setPen(pen) scene.addItem(path_item) path_item = QGraphicsPathItem(path2) pen = QPen(Qt.darkGray) pen.setCosmetic(True) path_item.setPen(pen) scene.addItem(path_item) timer = QTimer() timer.timeout.connect(view.update_last_plot)
def drawLines(self, qp): # print(self.t.elapsed()) pen = QPen(Qt.black, 2, Qt.SolidLine) pen_dash = QPen(Qt.black, 2, Qt.DotLine) # Vertical qp.setPen(pen) qp.drawLine(270, 0, 270, 600) # with grids ################## # qp.drawLine(280, 0, 280, 600) # qp.drawLine(290, 0, 290, 600) # qp.drawLine(300, 0, 300, 600) # qp.drawLine(310, 0, 310, 600) # qp.drawLine(320, 0, 320, 600) # with grids ################## qp.drawLine(330, 0, 330, 600) qp.drawLine(300, 0, 300, 270) qp.drawLine(300, 330, 300, 600) qp.setPen(pen_dash) qp.drawLine(280, 330, 280, 600) qp.drawLine(290, 330, 290, 600) qp.drawLine(310, 330, 310, 600) qp.drawLine(320, 330, 320, 600) qp.drawLine(280, 0, 280, 270) qp.drawLine(290, 0, 290, 270) qp.drawLine(310, 0, 310, 270) qp.drawLine(320, 0, 320, 270) # Tropical qp.setPen(pen) qp.drawLine(0, 270, 600, 270) # with grids ################## # qp.drawLine(0, 280, 600, 280) # qp.drawLine(0, 290, 600, 290) # qp.drawLine(0, 300, 600, 300) # qp.drawLine(0, 310, 600, 310) # qp.drawLine(0, 320, 600, 320) # with grids ################## qp.drawLine(0, 330, 600, 330) qp.drawLine(0, 300, 270, 300) qp.drawLine(330, 300, 600, 300) qp.setPen(pen_dash) qp.drawLine(0, 280, 270, 280) qp.drawLine(0, 290, 270, 290) qp.drawLine(0, 310, 270, 310) qp.drawLine(0, 320, 270, 320) qp.drawLine(330, 280, 600, 280) qp.drawLine(330, 290, 600, 290) qp.drawLine(330, 310, 600, 310) qp.drawLine(330, 320, 600, 320)
def setViewTheme(self, bgColor, brushColor, penColor): brushColor.setAlpha(40) penColor.setAlpha(100) self.fViewBg = bgColor self.fViewBrush = QBrush(brushColor) self.fViewPen = QPen(penColor, 1)
def drawRobotCallback(self, result): self.RobotListTable.setRowCount(0) #clear table for item in self.RobotShapes: self.scene.removeItem(item) self.RobotShapes.clear() self.AllRobotNames.clear() self.SupervisorSpecificRobotNames.clear() for item in result.robots: obSize = 70 shape = QGraphicsEllipseItem( int(item.pose.pose.pose.position.x * 100 - obSize / 2), -int(item.pose.pose.pose.position.y * 100 + obSize / 2), obSize, obSize) shape.setPen(QPen(self.black)) # separate the robots by "all" and "supervisor specific" if (item.supervisorID == self.id): self.SupervisorSpecificRobotNames.append(item.name) color = QColor(self.RobotTasks[item.currentTaskName][2]) shape.setBrush(QBrush(color, Qt.SolidPattern)) self.RobotListTable.insertRow(self.RobotListTable.rowCount()) self.RobotListTable.setItem(self.RobotListTable.rowCount() - 1, 0, QTableWidgetItem(item.name)) self.RobotListTable.setItem( self.RobotListTable.rowCount() - 1, 1, QTableWidgetItem(item.currentTaskName)) self.RobotListTable.setItem(self.RobotListTable.rowCount() - 1, 2, QTableWidgetItem(item.status)) icon_item = QTableWidgetItem() icon_item.setIcon(QIcon(cameraIcon)) self.RobotListTable.setItem(self.RobotListTable.rowCount() - 1, 3, icon_item) else: color = QColor(self.RobotTasks[item.currentTaskName][2]) shape.setBrush(QBrush(color, Qt.Dense3Pattern)) self.scene.addItem(shape) self.RobotShapes.append(shape) self.AllRobotNames.append(item.name) label = QGraphicsTextItem(item.name) label.setX(int(item.pose.pose.pose.position.x * 100)) label.setY(-int(item.pose.pose.pose.position.y * 100 + obSize * 1.2)) font = QFont("Bavaria") font.setPointSize(18) font.setWeight(QFont.Bold) label.setDefaultTextColor(color) label.setFont(font) self.scene.addItem(label) self.RobotShapes.append(label) quat = item.pose.pose.pose.orientation siny_cosp = 2 * (quat.w * quat.z + quat.x * quat.y) cosy_cosp = 1 - 2 * (quat.y * quat.y + quat.z * quat.z) yaw = math.atan2(siny_cosp, cosy_cosp) #making the arrow arrowLines = self.makeArrow(item.pose.pose.pose.position.x * 100, item.pose.pose.pose.position.y * 100, yaw, obSize) for line in arrowLines: self.scene.addItem(line) self.RobotShapes.append(line) type = item.currentTask.taskName if self.RobotTasks[type][1] == "True": X = item.currentTask.X * 100 Y = item.currentTask.Y * -100 shapes = self.makeTarget(X, Y, 50, self.red) for shape in shapes: self.RobotShapes.append(shape) self.scene.addItem(shape) label = QGraphicsTextItem(item.name + " Goal") label.setX(int(X)) label.setY(int(Y - obSize)) font = QFont("Bavaria") font.setPointSize(18) font.setWeight(QFont.Bold) label.setDefaultTextColor(self.red) label.setFont(font) self.scene.addItem(label) self.RobotShapes.append(label)
def __init__(self, parent=None): super(Widget, self).__init__(parent) self.setWindowTitle('Financieële grafieken externe werken') self.setWindowIcon(QIcon('./images/logos/logo.jpg')) self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint) grid = QGridLayout() grid.setSpacing(20) metadata = MetaData() resultaten = Table('resultaten', metadata, Column('resID', Integer(), primary_key=True), Column('statusweek', String), Column('btotaal', Float), Column('wtotaal', Float), Column('betaald_bedrag', Float), Column('meerminderwerk', Float), Column('onderhandenwerk', Float), Column('aanneemsom', Float), Column('blonen', Float), Column('wlonen', Float), Column('bmaterialen', Float), Column('wmaterialen', Float), Column('bmaterieel', Float), Column('wmaterieel', Float), Column('bprojectkosten', Float), Column('wprojectkosten', Float), Column('binhuur', Float), Column('winhuur', Float), Column('bdiensten', Float), Column('wdiensten', Float), Column('bruto_winst', Float), Column('boekweek', String)) params = Table('params', metadata, Column('paramID', Integer(), primary_key=True), Column('tarief', String)) engine = create_engine( 'postgresql+psycopg2://postgres@localhost/bisystem') con = engine.connect() selpar1 = select([params]).where(params.c.paramID == 97) rppar1 = con.execute(selpar1).first() bo_incr = rppar1[1] / 52 #begrote omzet per week selpar2 = select([params]).where(params.c.paramID == 98) rppar2 = con.execute(selpar2).first() bw_incr = rppar2[1] / 52 #begrote winst per week jaar = jrwk[0:4] engine = create_engine( 'postgresql+psycopg2://postgres@localhost/bisystem') con = engine.connect() selres = select([resultaten]).where(and_(resultaten.c.boekweek == jrwk,\ resultaten.c.statusweek.like(jaar+'%'))).order_by(resultaten.c.statusweek) rpres = con.execute(selres) if keuze == '1': s1 = 2 s2 = 3 t1 = 'Kosten totaal begroot' t2 = 'Kosten totaal werkelijk' t3 = 'Kosten totaal ' c1 = Qt.red c2 = Qt.blue ysch = 160000000 elif keuze == '2': s1 = 8 s2 = 9 t1 = 'Lonen begroot' t2 = 'Lonen werkelijk' t3 = 'Lonen ' c1 = Qt.green c2 = Qt.darkBlue ysch = 100000000 elif keuze == '3': s1 = 10 s2 = 11 t1 = 'Materialen begroot' t2 = 'Materialen werkelijk' t3 = 'Materialen' c1 = Qt.cyan c2 = Qt.magenta ysch = 60000000 elif keuze == '4': s1 = 12 s2 = 13 t1 = 'Materiëel begroot' t2 = 'Materiëel werkelijk' t3 = 'Materiëel ' c1 = Qt.darkYellow c2 = Qt.darkGreen ysch = 20000000 elif keuze == '5': s1 = 16 s2 = 17 t1 = 'Inhuur begroot' t2 = 'Inhuur werkelijk' t3 = 'Inhuur ' c1 = Qt.darkBlue c2 = Qt.darkRed ysch = 30000000 elif keuze == '6': s1 = 18 s2 = 19 t1 = 'Diensten begroot' t2 = 'Diensten werkelijk' t3 = 'Diensten ' c1 = Qt.red c2 = Qt.blue ysch = 30000000 elif keuze == '7': s1 = 14 s2 = 15 t1 = 'Projektkosten begroot' t2 = 'Projektkosten werkelijk' t3 = 'Projektkosten ' c1 = Qt.darkYellow c2 = Qt.darkCyan ysch = 10000000 elif keuze == '8': y3 = [ 0, ] y3val = 0 x1 = [ 0, ] xval1 = 0 # prognose winst for teller in range(0, 53): y3val = y3val + bw_incr y3 = y3 + [(y3val)] xval1 = xval1 + 1 x1 = x1 + [(xval1)] s1 = 20 s2 = 20 t1 = 'Bruto winst prognose' t2 = 'Bruto winst actueel' t3 = 'Bruto winst - prognose / aktueel ' c1 = Qt.darkCyan c2 = Qt.darkMagenta ysch = 20000000 elif keuze == '9': s1 = 6 s2 = 4 t1 = 'Onderhandenwerk' t2 = 'Betaald bedrag' t3 = 'Onderhandenwerk - Betaald bedrag ' c1 = Qt.yellow c2 = Qt.green ysch = 160000000 elif keuze == 'A': y4 = [ 0, ] y4val = 0 x2 = [ 0, ] xval2 = 0 #prognose omzet for teller in range(0, 53): y4val = y4val + bo_incr y4 = y4 + [(y4val)] xval2 = xval2 + 1 x2 = x2 + [(xval2)] s1 = 7 s2 = 7 t1 = 'Omzet prognose' t2 = 'Omzet aktueel' t3 = 'Omzet ' c1 = Qt.red c2 = Qt.blue ysch = 160000000 elif keuze == 'B': s1 = 20 s2 = 5 t1 = 'Bruto winst werkelijk' t2 = 'Meerminderwerk' t3 = 'Bruto winst werkelijk / Meerminderwerk ' c1 = Qt.darkRed c2 = Qt.darkBlue ysch = 30000000 x = [ 0, ] y1 = [ 0, ] y2 = [ 0, ] idx = 0 yval1 = 0 yval2 = 0 for row in rpres: yval1 = y1[idx] + row[s1] y1 = y1 + [(yval1)] yval2 = y2[idx] + row[s2] y2 = y2 + [(yval2)] x = x + [(int(row[1][4:]))] idx += 1 series1 = QLineSeries() if keuze == '8': for t, val in zip(x1, y3): series1.append(int(t), val) elif keuze == 'A': for t, val in zip(x2, y4): series1.append(int(t), val) else: for t, val in zip(x, y1): series1.append(int(t), val) series2 = QLineSeries() for t, val in zip(x, y2): series2.append(int(t), val) chart = QChart() chart.addSeries(series1) chart.addSeries(series2) series1.setColor(QColor(c1)) series2.setColor(QColor(c2)) series1.setName(t1) series2.setName(t2) chart.legend().setVisible(True) font = QFont() font.setPixelSize(22) chart.setTitleFont(font) chart.setTitle(t3 + jaar) chart.setTitleBrush(QBrush(Qt.black)) chart.legend().setLabelBrush(QColor(Qt.black)) axisX = QCategoryAxis() axisY = QCategoryAxis() axisX.setTitleText('Jaar ' + jaar + ' - Weeknummers') axisX.setTitleBrush(QBrush(Qt.black)) font = QFont("Sans Serif") axisX.setTitleFont(font) axisPen = QPen(QColor(100, 100, 100)) # 100,100,100 axisPen.setWidth(3) axisX.setLinePen(axisPen) axisY.setLinePen(axisPen) axisBrush = QBrush(Qt.black) axisX.setLabelsBrush(axisBrush) axisY.setLabelsBrush(axisBrush) axisX.setGridLineVisible(False) axisY.setGridLineVisible(True) axisX.setShadesBrush(QBrush(QColor(245, 245, 245))) axisX.setShadesVisible(True) for x in range(1, 54): axisX.append(jaar + "-" + ("0" + str(x))[-2:], x) axisX.setRange(0, 53) axisX.setLabelsAngle(-90) axisY = QValueAxis() axisY.setTickCount(33) axisY.setTitleText("Bedragen in Euro") axisY.setTitleFont(font) axisY.setLabelFormat('%d') axisY.setTitleBrush(QBrush(Qt.black)) axisY.setRange(0, ysch) #disable for automatic Y scale #axisY.applyNiceNumbers() #enable by automatic Y scale Lfont = QFont("Sans Serif") Dfont = QFont("Sans Serif") Lfont.setPixelSize(10) Dfont.setPixelSize(10) axisX.setLabelsFont(Dfont) axisY.setLabelsFont(Lfont) axisPen = QPen(QColor('black')) axisPen = QPen() axisPen.setWidth(2) axisX.setLinePen(axisPen) axisX.setLabelsColor(QColor('black')) axisY.setLinePen(axisPen) axisY.setLabelsColor(QColor('black')) chart.addAxis(axisX, Qt.AlignBottom) series1.attachAxis(axisX) axisX.setLabelsAngle(-90) chart.addAxis(axisY, Qt.AlignLeft) series1.attachAxis(axisY) series2.attachAxis(axisY) self.chartView = QChartView(chart) self.chartView.setRenderHint(QPainter.Antialiasing) buttonPreview = QPushButton('Afdrukvoorbeeld') buttonPreview.clicked.connect(self.handle_preview) buttonPreview.setStyleSheet( "color: black; background-color: gainsboro") buttonPrint = QPushButton('Printen') buttonPrint.clicked.connect(self.handle_print) buttonPrint.setStyleSheet( "color: black; background-color: gainsboro") buttonSluit = QPushButton('Sluiten') buttonSluit.clicked.connect(lambda: sluit(self, m_email)) buttonSluit.setStyleSheet( "color: black; background-color: gainsboro") grid.addWidget(self.chartView, 0, 0, 0, 3) grid.addWidget(buttonSluit, 1, 0) grid.addWidget(buttonPrint, 1, 1) grid.addWidget(buttonPreview, 1, 2) self.setLayout(grid) self.setGeometry(200, 40, 1395, 930)
def setPen(self, qp, penColor): pen = QPen(penColor, EDGE_LINE_WIDTH, Qt.SolidLine) qp.setPen(pen)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # os.chdir('./')# Set directory to current folder. self.setFont(QFont("Arial")) self.setMinimumSize(1200,850) self.setWindowTitle("PMTWidget") self.layout = QGridLayout(self) #------------------------Initiating class------------------- self.pmtTest = pmtimagingTest() self.pmtTest_contour = pmtimagingTest_contour() self.savedirectory = r'M:\tnw\ist\do\projects\Neurophotonics\Brinkslab\Data\Octoscope\pmt_image_default_dump' self.prefixtextboxtext = '_fromGalvoWidget' #************************************************************************************************************************************** #-------------------------------------------------------------------------------------------------------------------------------------- #-----------------------------------------------------------GUI for PMT tab------------------------------------------------------------ #-------------------------------------------------------------------------------------------------------------------------------------- #************************************************************************************************************************************** pmtimageContainer = QGroupBox("PMT image") self.pmtimageLayout = QGridLayout() self.pmtvideoWidget = pg.ImageView() self.pmtvideoWidget.ui.roiBtn.hide() self.pmtvideoWidget.ui.menuBtn.hide() self.pmtvideoWidget.resize(400,400) self.pmtimageLayout.addWidget(self.pmtvideoWidget, 0, 0) pmtroiContainer = QGroupBox("PMT ROI") self.pmtimageroiLayout = QGridLayout() self.pmt_roiwidget = pg.GraphicsLayoutWidget() self.pmt_roiwidget.resize(150,150) self.pmt_roiwidget.addLabel('ROI', row=0, col=0) # create ROI self.vb_2 = self.pmt_roiwidget.addViewBox(row=1, col=0, lockAspect=True, colspan=1) self.vb_2.name = 'ROI' self.pmtimgroi = pg.ImageItem() self.vb_2.addItem(self.pmtimgroi) #self.roi = pg.RectROI([20, 20], [20, 20], pen=(0,9)) #r1 = QRectF(0, 0, 895, 500) ROIpen = QPen() # creates a default pen ROIpen.setStyle(Qt.DashDotLine) ROIpen.setWidth(0.5) ROIpen.setBrush(QColor(0,161,255)) self.roi = pg.PolyLineROI([[0,0], [80,0], [80,80], [0,80]], closed=True, pen=ROIpen)#, maxBounds=r1 #self.roi.addScaleHandle([1,0], [1, 0]) self.roi.sigHoverEvent.connect(lambda: self.show_handle_num()) # update handle numbers self.pmtvb = self.pmtvideoWidget.getView() self.pmtimageitem = self.pmtvideoWidget.getImageItem() self.pmtvb.addItem(self.roi)# add ROIs to main image self.pmtimageroiLayout.addWidget(self.pmt_roiwidget, 0, 0) pmtimageContainer.setMinimumWidth(850) pmtroiContainer.setMaximumHeight(380) # pmtroiContainer.setMaximumWidth(300) pmtimageContainer.setLayout(self.pmtimageLayout) pmtroiContainer.setLayout(self.pmtimageroiLayout) #----------------------------Contour----------------------------------- pmtContourContainer = QGroupBox("Contour selection") pmtContourContainer.setFixedWidth(280) self.pmtContourLayout = QGridLayout() #contour_Description = QLabel("Handle number updates when parking mouse cursor upon ROI. Points in contour are divided evenly between handles.") #contour_Description.setStyleSheet('color: blue') #self.pmtContourLayout.addWidget(contour_Description,0,0) self.pmt_handlenum_Label = QLabel("Handle number: ") self.pmtContourLayout.addWidget(self.pmt_handlenum_Label,1,0) self.contour_strategy = QComboBox() self.contour_strategy.addItems(['Manual','Uniform']) self.pmtContourLayout.addWidget(self.contour_strategy, 1, 1) self.pointsinContour = QSpinBox(self) self.pointsinContour.setMinimum(1) self.pointsinContour.setMaximum(1000) self.pointsinContour.setValue(100) self.pointsinContour.setSingleStep(100) self.pmtContourLayout.addWidget(self.pointsinContour, 2, 1) self.pmtContourLayout.addWidget(QLabel("Points in contour:"), 2, 0) self.contour_samprate = QSpinBox(self) self.contour_samprate.setMinimum(0) self.contour_samprate.setMaximum(1000000) self.contour_samprate.setValue(50000) self.contour_samprate.setSingleStep(50000) self.pmtContourLayout.addWidget(self.contour_samprate, 3, 1) self.pmtContourLayout.addWidget(QLabel("Sampling rate:"), 3, 0) self.generate_contour_sacn = StylishQT.generateButton() self.pmtContourLayout.addWidget(self.generate_contour_sacn, 4, 1) self.generate_contour_sacn.clicked.connect(lambda: self.generate_contour()) self.do_contour_sacn = StylishQT.runButton("Contour") self.do_contour_sacn.setFixedHeight(32) self.pmtContourLayout.addWidget(self.do_contour_sacn, 5, 0) self.do_contour_sacn.clicked.connect(lambda:self.buttonenabled('contourscan', 'start')) self.do_contour_sacn.clicked.connect(lambda: self.measure_pmt_contourscan()) self.stopButton_contour = StylishQT.stop_deleteButton() self.stopButton_contour.setFixedHeight(32) self.stopButton_contour.clicked.connect(lambda:self.buttonenabled('contourscan', 'stop')) self.stopButton_contour.clicked.connect(lambda: self.stopMeasurement_pmt_contour()) self.stopButton_contour.setEnabled(False) self.pmtContourLayout.addWidget(self.stopButton_contour, 5, 1) pmtContourContainer.setLayout(self.pmtContourLayout) #----------------------------Control----------------------------------- controlContainer = QGroupBox("Galvo Scanning Panel") controlContainer.setFixedWidth(280) self.controlLayout = QGridLayout() self.pmt_fps_Label = QLabel("Per frame: ") self.controlLayout.addWidget(self.pmt_fps_Label, 5, 0) self.saveButton_pmt = StylishQT.saveButton() self.saveButton_pmt.clicked.connect(lambda: self.saveimage_pmt()) self.controlLayout.addWidget(self.saveButton_pmt, 5, 1) self.startButton_pmt = StylishQT.runButton("") self.startButton_pmt.setFixedHeight(32) self.startButton_pmt.setCheckable(True) self.startButton_pmt.clicked.connect(lambda:self.buttonenabled('rasterscan', 'start')) self.startButton_pmt.clicked.connect(lambda: self.measure_pmt()) self.controlLayout.addWidget(self.startButton_pmt, 6, 0) self.stopButton = StylishQT.stop_deleteButton() self.stopButton.setFixedHeight(32) self.stopButton.clicked.connect(lambda:self.buttonenabled('rasterscan', 'stop')) self.stopButton.clicked.connect(lambda: self.stopMeasurement_pmt()) self.stopButton.setEnabled(False) self.controlLayout.addWidget(self.stopButton, 6, 1) #-----------------------------------Galvo scanning------------------------------------------------------------------------ self.textboxAA_pmt = QSpinBox(self) self.textboxAA_pmt.setMinimum(0) self.textboxAA_pmt.setMaximum(1000000) self.textboxAA_pmt.setValue(500000) self.textboxAA_pmt.setSingleStep(100000) self.controlLayout.addWidget(self.textboxAA_pmt, 1, 1) self.controlLayout.addWidget(QLabel("Sampling rate:"), 1, 0) #self.controlLayout.addWidget(QLabel("Galvo raster scanning : "), 1, 0) self.textbox1B_pmt = QSpinBox(self) self.textbox1B_pmt.setMinimum(-10) self.textbox1B_pmt.setMaximum(10) self.textbox1B_pmt.setValue(3) self.textbox1B_pmt.setSingleStep(1) self.controlLayout.addWidget(self.textbox1B_pmt, 2, 1) self.controlLayout.addWidget(QLabel("Volt range:"), 2, 0) self.Scanning_pixel_num_combobox = QSpinBox(self) self.Scanning_pixel_num_combobox.setMinimum(0) self.Scanning_pixel_num_combobox.setMaximum(1000) self.Scanning_pixel_num_combobox.setValue(500) self.Scanning_pixel_num_combobox.setSingleStep(244) self.controlLayout.addWidget(self.Scanning_pixel_num_combobox, 3, 1) self.controlLayout.addWidget(QLabel("Pixel number:"), 3, 0) self.textbox1H_pmt = QSpinBox(self) self.textbox1H_pmt.setMinimum(1) self.textbox1H_pmt.setMaximum(20) self.textbox1H_pmt.setValue(1) self.textbox1H_pmt.setSingleStep(1) self.controlLayout.addWidget(self.textbox1H_pmt, 4, 1) self.controlLayout.addWidget(QLabel("average over:"), 4, 0) controlContainer.setLayout(self.controlLayout) #---------------------------Set tab1 layout--------------------------- # pmtmaster = QGridLayout() self.layout.addWidget(pmtimageContainer, 0,0,3,1) self.layout.addWidget(pmtroiContainer,1,1) self.layout.addWidget(pmtContourContainer,2,1) self.layout.addWidget(controlContainer,0,1)
def paint(self, painter, option, widget): # paint a bounding rectangle for undo/redo highlighting painter.setPen(QPen(Qt.blue, 0.5, style=Qt.DotLine)) painter.drawRoundedRect(option.rect, 10, 10) # paint the normal item with the default 'paint' method super(GhostComment, self).paint(painter, option, widget)
def __init__(self, points=[], pen=QPen(Qt.black, 0), title="LinePlot"): self._points = points self._pen = pen self._repaintIndex = 0 self._title = title self._hidden = False
def __init__(self, line, parent=None): super(myLineItem, self).__init__(line, parent) self.setPen(QPen(Qt.black, 2))
def paintEvent(self, event): super().paintEvent(event) rect = QRect(self.x0, self.y0, self.x1 - self.x0, self.y1 - self.y0) painter = QPainter(self) painter.setPen(QPen(Qt.red, 2, Qt.SolidLine)) painter.drawRect(rect)
def __init__(self, circle, parent=None): super(myCircleItem, self).__init__(circle, parent) self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | QtWidgets.QGraphicsItem.ItemIsSelectable) self.setPen(QPen(Qt.red, 2)) self.setBrush(QBrush(Qt.Dense7Pattern))
def _set_render_parameters(self): # get size of widget size = self.size() w = size.width() h = size.height() # starting coordinates of drawing # TODO: modify for horizontal/vertical alignment #----------------------------------------------------------------------- widget_x = 0.0 widget_y = 0.0 # x-axis tick labels #----------------------------------------------------------------------- labelFontMetrics = QFontMetrics(self._labelFont) xaxis_min = min(self._xMin, self._xMax) xaxis_max = max(self._xMin, self._xMax) self._xaxis_ticks_value = [] self._xaxis_ticks_text_size = [] tick_value = self._xOriginValue while tick_value < xaxis_max: if tick_value > xaxis_min: self._xaxis_ticks_value.append(tick_value) tick_text = "{:.1f}".format(tick_value) self._xaxis_ticks_text_size.append( labelFontMetrics.size(Qt.TextSingleLine, tick_text)) tick_value += self._xTickInterval tick_value = self._xOriginValue - self._xTickInterval while tick_value > xaxis_min: if tick_value < xaxis_max: self._xaxis_ticks_value.append(tick_value) tick_text = "{:.1f}".format(tick_value) self._xaxis_ticks_text_size.append( labelFontMetrics.size(Qt.TextSingleLine, tick_text)) tick_value -= self._xTickInterval xaxis_ticks_text_max_height = max( [s.height() for s in self._xaxis_ticks_text_size]) xaxis_ticks_text_max_width = max( [s.width() for s in self._xaxis_ticks_text_size]) # y-axis tick labels #----------------------------------------------------------------------- yaxis_min = min(self._yMin, self._yMax) yaxis_max = max(self._yMin, self._yMax) self._yaxis_ticks_value = [] self._yaxis_ticks_text_size = [] tick_value = self._yOriginValue while tick_value < yaxis_max: if tick_value > yaxis_min: self._yaxis_ticks_value.append(tick_value) tick_text = "{:.1f}".format(tick_value) self._yaxis_ticks_text_size.append( labelFontMetrics.size(Qt.TextSingleLine, tick_text)) tick_value += self._yTickInterval tick_value = self._yOriginValue - self._yTickInterval while tick_value > yaxis_min: if tick_value < yaxis_max: self._yaxis_ticks_value.append(tick_value) tick_text = "{:.1f}".format(tick_value) self._yaxis_ticks_text_size.append( labelFontMetrics.size(Qt.TextSingleLine, tick_text)) tick_value -= self._yTickInterval yaxis_ticks_text_max_height = max( [s.height() for s in self._yaxis_ticks_text_size]) yaxis_ticks_text_max_width = max( [s.width() for s in self._yaxis_ticks_text_size]) * 1.1 # axes #----------------------------------------------------------------------- self._axes_tick_pen = QPen(Qt.black, 1.0, Qt.DashLine) self._axes_tick_brush = QBrush(Qt.NoBrush) #self._axes_origin_pen = QPen(Qt.black, 2.0, Qt.DashDotLine) self._axes_origin_pen = QPen(Qt.black, 2.0, Qt.SolidLine) self._axes_origin_brush = QBrush(Qt.NoBrush) # bounding box for plot #----------------------------------------------------------------------- self._bbox_pen = QPen(Qt.black, 1.0) self._bbox_brush = QBrush(Qt.NoBrush) self._bbox_x0 = widget_x + yaxis_ticks_text_max_width self._bbox_x1 = w - 1 self._bbox_y0 = widget_y self._bbox_y1 = h - xaxis_ticks_text_max_height - 1 self._bbox_rect = QRectF(QPointF(self._bbox_x0, self._bbox_y0), QPointF(self._bbox_x1, self._bbox_y1)) # origin lines #----------------------------------------------------------------------- self._xaxis_origin_x = map_value_to_scale(self._xOriginValue, self._xMin, self._xMax, self._bbox_x0, self._bbox_x1) self._xaxis_origin_line = QLineF( QPointF(self._xaxis_origin_x, self._bbox_y0), QPointF(self._xaxis_origin_x, self._bbox_y1)) self._yaxis_origin_y = map_value_to_scale(self._yOriginValue, self._yMin, self._yMax, self._bbox_y1, self._bbox_y0) self._yaxis_origin_line = QLineF( QPointF(self._bbox_x0, self._yaxis_origin_y), QPointF(self._bbox_x1, self._yaxis_origin_y)) # x-axis ticks #----------------------------------------------------------------------- self._xaxis_ticks = [] self._xaxis_ticks_text = [] self._xaxis_ticks_text_rect = [] for tick_value in self._xaxis_ticks_value: # define the tick lines to draw tick_x = map_value_to_scale(tick_value, self._xMin, self._xMax, self._bbox_x0, self._bbox_x1) tick_line = QLineF(QPointF(tick_x, self._bbox_y0), QPointF(tick_x, self._bbox_y1)) self._xaxis_ticks.append(tick_line) # define the tick labels to draw tick_text = "{:.1f}".format(tick_value) tick_size = labelFontMetrics.size(Qt.TextSingleLine, tick_text) tick_rect = QRectF( QPointF(tick_x - (tick_size.width() / 2.0), self._bbox_y1), QSizeF(tick_size)) self._xaxis_ticks_text.append(tick_text) self._xaxis_ticks_text_rect.append(tick_rect) # y-axis ticks #----------------------------------------------------------------------- self._yaxis_ticks = [] self._yaxis_ticks_text = [] self._yaxis_ticks_text_rect = [] for tick_value in self._yaxis_ticks_value: # define the tick lines to draw tick_y = map_value_to_scale(tick_value, self._yMin, self._yMax, self._bbox_y1, self._bbox_y0) tick_line = QLineF(QPointF(self._bbox_x0, tick_y), QPointF(self._bbox_x1, tick_y)) self._yaxis_ticks.append(tick_line) # define the tick labels to draw tick_text = "{:.1f}".format(tick_value) tick_size = labelFontMetrics.size(Qt.TextSingleLine, tick_text) tick_rect = QRectF( QPointF(widget_x, tick_y - (tick_size.height() / 2.0)), QSizeF(yaxis_ticks_text_max_width, tick_size.height())) self._yaxis_ticks_text.append(tick_text) self._yaxis_ticks_text_rect.append(tick_rect) # define plot traces #----------------------------------------------------------------------- for plot_key in self._plots.keys(): self._plot_points[plot_key] = [] for plot_value in self._plots[plot_key]: plot_value_x = map_value_to_scale(plot_value[0], self._xMin, self._xMax, self._bbox_x0, self._bbox_x1) plot_value_y = map_value_to_scale(plot_value[1], self._yMin, self._yMax, self._bbox_y1, self._bbox_y0) self._plot_points[plot_key].append( QPointF(plot_value_x, plot_value_y))
def paintEvent(self, event): super(WinMenuButton, self).paintEvent(event) if not self.show_foreground: return # 不显示前景 w = self._w h = self._h dx = self.offset_pos.x() dy = self.offset_pos.y() painter = QPainter(self) painter.setPen(QPen(self.icon_color)) if self.click_ani_appearing: pro = self.click_ani_progress / 100.0 if not self.getState(): pro = 1 - pro len = w/3 l = self._l+w/3 r = self._l+w*2/3 t = self._t+h/3 + pro*h/3 painter.drawLine(QPoint(l+dx/4,t+dy/4), QPoint(r+dx/4,t+dy/4)) l = self._l+w/3+pro*w/24 r = self._l+w*2/3-pro*w/24 t = self._t+w/2+pro*h*5/18 painter.drawLine(QPoint(l+dx/2,t+dy/2), QPoint(r+dx/2,t+dy/2)) l = self._l+w/3+pro*w/12 r = self._l+w*2/3-pro*w/12 t = self._t+w*2/3+pro*h*2/9 painter.drawLine(QPoint(l+dx,t+dy), QPoint(r+dx,t+dy)) ''' half_len = w/6 # self.quick_sqrt(w/3*w/3 + h/3*h/3) / 2 # 长度 painter.setRenderHint(QPainter.Antialiamath.sing, True) # 第一个点 mx = w/2 my = h/3 + pro*h/6 angle = pro*PI*5/4 sx = mx - half_len*math.cos(angle) sy = my - half_len*math.sin(angle) ex = mx + half_len*math.cos(angle) ey = my + half_len*math.sin(angle) painter.drawLine(QPoint(sx,sy), QPoint(ex,ey)) # 第三个点 mx = w/2 my = h*2/3 - pro*h/6 angle = pro*PI*3/4 sx = mx - half_len*math.cos(angle) sy = my - half_len*math.sin(angle) ex = mx + half_len*math.cos(angle) ey = my + half_len*math.sin(angle) painter.drawLine(QPoint(sx,sy), QPoint(ex,ey)) # 第二个点(设置透明度) mx = w/2 my = h/2 angle = pro*PI sx = mx - half_len*math.cos(angle) sy = my - half_len*math.sin(angle) ex = mx + half_len*math.cos(angle) ey = my + half_len*math.sin(angle) color = QColor(self.icon_color) color.setAlpha(color.alpha() * (1-pro)) painter.setPen(QPen(color)) painter.drawLine(QPoint(sx,sy), QPoint(ex,ey)) ''' elif self.getState(): painter.drawLine(self._l+w/3+dx/4, self._t+h*2/3+dy/4, w*2/3+dx/4,h*2/3+dy/4) painter.drawLine(self._l+w/3+w/24+dx/2, self._t+h*7/9+dy/2, w*2/3-w/24+dx/2, h*7/9+dy/2) painter.drawLine(self._l+w/3+w/12+dx, self._t+h*8/9+dy, w*2/3-w/12+dx, h*8/9+dy) ''' painter.drawLine(QPoint(0.39*w, 0.39*h), QPoint(0.61*w, 0.61*h)) painter.drawLine(QPoint(0.39*w, 0.61*h), QPoint(0.61*w, 0.39*h)) ''' else: painter.drawLine(QPoint(self._l+w/3+dx/4,self._t+h/3+dy/4), QPoint(self._l+w*2/3+dx/4,self._t+h/3+dy/4)) painter.drawLine(QPoint(self._l+w/3+dx/2,self._t+h/2+dy/2), QPoint(self._l+w*2/3+dx/2,self._t+h/2+dy/2)) painter.drawLine(QPoint(self._l+w/3+dx,self._t+h*2/3+dy), QPoint(self._l+w*2/3+dx,self._t+h*2/3+dy))
def __init__(self, parent=None): super(ThemePage, self).__init__(parent) self.parent = parent self.setObjectName('settingsthemepage') mainLayout = QVBoxLayout() mainLayout.setSpacing(10) pen = QPen( QColor('#4D5355' if self.parent.theme == 'dark' else '#B9B9B9')) pen.setWidth(2) theme_light = QPixmap(':/images/theme-light.png', 'PNG') painter = QPainter(theme_light) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawRect(0, 0, theme_light.width(), theme_light.height()) theme_dark = QPixmap(':/images/theme-dark.png', 'PNG') painter = QPainter(theme_dark) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawRect(0, 0, theme_dark.width(), theme_dark.height()) self.lightRadio = QRadioButton(self) self.lightRadio.setIcon(QIcon(theme_light)) self.lightRadio.setIconSize(QSize(165, 121)) self.lightRadio.setCursor(Qt.PointingHandCursor) self.lightRadio.clicked.connect(self.switchTheme) self.lightRadio.setChecked(self.parent.theme == 'light') self.darkRadio = QRadioButton(self) self.darkRadio.setIcon(QIcon(theme_dark)) self.darkRadio.setIconSize(QSize(165, 121)) self.darkRadio.setCursor(Qt.PointingHandCursor) self.darkRadio.clicked.connect(self.switchTheme) self.darkRadio.setChecked(self.parent.theme == 'dark') themeLayout = QGridLayout() themeLayout.setColumnStretch(0, 1) themeLayout.addWidget(self.lightRadio, 0, 1) themeLayout.addWidget(self.darkRadio, 0, 3) themeLayout.addWidget(QLabel('Light', self), 1, 1, Qt.AlignHCenter) themeLayout.setColumnStretch(2, 1) themeLayout.addWidget(QLabel('Dark', self), 1, 3, Qt.AlignHCenter) themeLayout.setColumnStretch(4, 1) themeGroup = QGroupBox('Theme') themeGroup.setLayout(themeLayout) mainLayout.addWidget(themeGroup) index_leftRadio = QRadioButton('Clips on left') index_leftRadio.setToolTip('Display Clip Index on the left hand side') index_leftRadio.setCursor(Qt.PointingHandCursor) index_leftRadio.setChecked(self.parent.parent.indexLayout == 'left') index_rightRadio = QRadioButton('Clips on right') index_rightRadio.setToolTip( 'Display Clip Index on the right hand side') index_rightRadio.setCursor(Qt.PointingHandCursor) index_rightRadio.setChecked(self.parent.parent.indexLayout == 'right') index_buttonGroup = QButtonGroup(self) index_buttonGroup.addButton(index_leftRadio, 1) index_buttonGroup.addButton(index_rightRadio, 2) # noinspection PyUnresolvedReferences index_buttonGroup.buttonClicked[int].connect( self.parent.parent.setClipIndexLayout) indexLayout = QHBoxLayout() indexLayout.addWidget(index_leftRadio) indexLayout.addWidget(index_rightRadio) layoutGroup = QGroupBox('Layout') layoutGroup.setLayout(indexLayout) mainLayout.addWidget(layoutGroup) toolbar_labels = self.parent.settings.value('toolbarLabels', 'beside', type=str) toolbar_notextRadio = QRadioButton('No text (buttons only)', self) toolbar_notextRadio.setToolTip('No text (buttons only)') toolbar_notextRadio.setCursor(Qt.PointingHandCursor) toolbar_notextRadio.setChecked(toolbar_labels == 'none') toolbar_underRadio = QRadioButton('Text under buttons', self) toolbar_underRadio.setToolTip('Text under buttons') toolbar_underRadio.setCursor(Qt.PointingHandCursor) toolbar_underRadio.setChecked(toolbar_labels == 'under') toolbar_besideRadio = QRadioButton('Text beside buttons', self) toolbar_besideRadio.setToolTip('Text beside buttons') toolbar_besideRadio.setCursor(Qt.PointingHandCursor) toolbar_besideRadio.setChecked(toolbar_labels == 'beside') toolbar_buttonGroup = QButtonGroup(self) toolbar_buttonGroup.addButton(toolbar_besideRadio, 1) toolbar_buttonGroup.addButton(toolbar_underRadio, 2) toolbar_buttonGroup.addButton(toolbar_notextRadio, 3) # noinspection PyUnresolvedReferences toolbar_buttonGroup.buttonClicked[int].connect(self.setLabelStyle) toolbarLayout = QGridLayout() toolbarLayout.addWidget(toolbar_besideRadio, 0, 0) toolbarLayout.addWidget(toolbar_underRadio, 0, 1) toolbarLayout.addWidget(toolbar_notextRadio, 1, 0) toolbarGroup = QGroupBox('Toolbar') toolbarGroup.setLayout(toolbarLayout) mainLayout.addWidget(toolbarGroup) nativeDialogsCheckbox = QCheckBox('Use native dialogs', self) nativeDialogsCheckbox.setToolTip('Use native file dialogs') nativeDialogsCheckbox.setCursor(Qt.PointingHandCursor) nativeDialogsCheckbox.setChecked(self.parent.parent.nativeDialogs) nativeDialogsCheckbox.stateChanged.connect(self.setNativeDialogs) nativeDialogsLabel = QLabel( ''' <b>ON:</b> use native dialog widgets as provided by your operating system <br/> <b>OFF:</b> use a generic file open & save dialog widget provided by the Qt toolkit <br/><br/> <b>NOTE:</b> native dialogs should always be used if working ''', self) nativeDialogsLabel.setObjectName('nativedialogslabel') nativeDialogsLabel.setTextFormat(Qt.RichText) nativeDialogsLabel.setWordWrap(True) advancedLayout = QVBoxLayout() advancedLayout.addWidget(nativeDialogsCheckbox) advancedLayout.addWidget(nativeDialogsLabel) advancedGroup = QGroupBox('Advanced') advancedGroup.setLayout(advancedLayout) mainLayout.addWidget(advancedGroup) mainLayout.addStretch(1) self.setLayout(mainLayout)
def add_ellipse_animation(self, color: QColor, position: int = 0): ellipse = self.widget.scene().addEllipse(0, 0, 10, 10) ellipse.setPen(QPen(color, 0)) ellipse.setBrush(QBrush(color)) self.add_animation(ellipse, position)
def drawDagger(self, qp): pen = QPen(QColor(self.color), 2, Qt.SolidLine) qp.setPen(pen) qp.drawLines(self.line, self.line2)
def _draw_cone(self, x, y, diameter=10, color=QColor(100, 200, 0)): point = self.get_px_pos_from_m([x, y]) cone_pen = QPen(color, 2, Qt.SolidLine, Qt.RoundCap) cone_ellipse = self.addEllipse(point[0] - diameter / 2, point[1] - diameter / 2, diameter, diameter, cone_pen)
def paint(self, painter, option, index): """draw the individual lines in the layers control """ painter.save() color = QColor(187, 213, 255, 255) if index.row() % 2 == 0 else QColor(177, 223, 255, 255) # color = QColor(187, 213, 255, 255) painter.setPen(QPen(color)) painter.setFont(self.font) value = index.data(Qt.UserRole) text = index.data(Qt.DisplayRole) rect = option.rect # if we have a value, break out the animation order and other info animation_order = None if value: value, animation_order = value # if we have a point probe value, draw the filled bar to represent where it is in that layer's data range if value: value, bar, fmtd_str = value width = bar * float(rect.width()) right = QRect(rect.left(), rect.top(), int(width), rect.height()) painter.fillRect(right, color) super(LayerWidgetDelegate, self).paint(painter, option, index) # if this layer is selected, draw a colored rectangle to highlight it if option.state & QStyle.State_Selected and value: painter.fillRect(right, QColor(213, 187, 255, 96)) # draw the name of the layer painter.setPen(QPen(Qt.black)) painter.setFont(self.font) bounds = painter.drawText(rect.left() + LEFT_OFFSET, rect.top() + TOP_OFFSET, rect.width() - LEFT_OFFSET, CELL_HEIGHT / 2 - TOP_OFFSET, Qt.AlignLeft, text, ) # also draw the animation order if animation_order is not None: painter.setPen(QPen(Qt.white)) ao_rect = QRect(bounds.right(), rect.top() + TOP_OFFSET, rect.width() - bounds.right(), CELL_HEIGHT / 2 - TOP_OFFSET, ) # draw the text once to get the bounding rectangle bounds = painter.drawText(ao_rect, Qt.AlignRight, str(animation_order + 1), ) painter.fillRect(bounds, Qt.black) # draw the text a second time to make sure it appears in the rectangle painter.drawText(ao_rect, Qt.AlignRight, str(animation_order + 1), ) # if we have a point probe value, draw text with it's value if value: painter.setPen(Qt.darkBlue) theight = CELL_HEIGHT / 2 top = rect.top() + rect.height() - theight if width < rect.width() / 3: # place the text to the right of the bar instead of inside left = max(int(width), LEFT_OFFSET) right = rect.width() align = Qt.AlignLeft else: left = 0 right = width align = Qt.AlignRight painter.drawText(left, top, right - left, theight, align, fmtd_str) painter.restore()
def topo_show(self, List: list): logging.info('拓扑开始显示') icon_width = 32 root_node = self.getRoot(List) toponodes = [] toponodes.append(root_node) icons = [] icon_count = 0 sip.delete(self.graphicsView.scene) self.graphicsView.scene = QtWidgets.QGraphicsScene(0, 0, 1920, 1080) self.graphicsView.setScene(self.graphicsView.scene) self.graphicsView.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.graphicsView.setSceneRect(0, 0, 3840, 1160) # fix scene size 500 500 self.graphicsView.setRenderHint(QPainter.Antialiasing) ##设置视图的抗锯齿渲染模式。 self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) for node in toponodes: # for node in newList: (y, x) = topo_picture().icon_locate(node, icon_width, icon_width, 100, 100) #print("Node", node.getName(), x, y) if node == root_node: iconi = self.create_icon("cco", x, y) icons.append(iconi) iconi.setPos(x, y) icon_count = icon_count + 1 self.root_name = QGraphicsTextItem(str(node.getName())) #self.root_name.setFont(QFont("Times",6)) self.root_name.setDefaultTextColor(Qt.darkBlue) self.root_name.setPos(QPointF(x, y + icon_width / 2 + 7)) self.scene.addItem(self.root_name) else: xp = x + icon_width / 2 yp = y + icon_width / 2 node_father = node.getFather() (fy, fx) = topo_picture().icon_locate(node_father, icon_width, icon_width, 100, 100) fxp = fx + icon_width / 2 fyp = fy + icon_width / 2 self.scene.addLine(xp, yp, fxp, fyp, QPen(Qt.black)) # QApplication.processEvents() ky = fyp - yp kx = fxp - xp if ky != 0: k = kx / ky # 往直线上添加其与父节点之间的距离 self.context = QGraphicsTextItem(str(node.getLength())) self.context.setDefaultTextColor(Qt.darkCyan) if ky == 0 or k == 0: self.context.setPos( QPointF((xp + fxp - icon_width / 8) / 2, (yp + fyp - icon_width) / 2)) else: self.context.setPos( QPointF((xp + fxp + icon_width / 8) / 2, (yp + fyp - icon_width) / 2)) #self.context.setPos(QPointF((xp + fxp - icon_width) / 2, (yp + fyp - icon_width) / 2)) self.context.setFont(QFont("Times", 8)) self.scene.addItem(self.context) # QApplication.processEvents() if node.getisVirtualNode(): self.scene.addRect(x + icon_width / 2 - 4, y + icon_width / 2 - 4, 8, 8, QPen(Qt.blue), QBrush(Qt.darkBlue)) # QApplication.processEvents() else: iconi = self.create_icon("ste", x, y) icons.append(iconi) iconi.setPos(x, y) # 添加真实节点的名字 self.name = QGraphicsTextItem(str(node.getName()[-4:])) #self.name.setFont(QFont("Times", 6)) # self.name.setDefaultTextColor(QColor(0, 160, 230)) self.name.setDefaultTextColor(Qt.darkBlue) self.name.setPos(QPointF(x, y + icon_width / 2 + 7)) self.scene.addItem(self.name) # QApplication.processEvents() child = node.getFirstChild() while child is not None: for node_child in List: if child == node_child: toponodes.append(node_child) child = child.getRightBrother()
def __init__(self, parent=None): super(scatser, self).__init__(parent) self.hovered.connect(self.onHovered) self.pen = QPen(Qt.black)
def paintEvent(self, QPaintEvent): """ 绘制背景 """ super().paintEvent(QPaintEvent) painter = QPainter(self) painter.setPen(QPen(QColor(229, 229, 229))) painter.drawLine(30, 176, self.width(), 176)
def paintEvent(self, objQPaintEvent): p = QPainter() p.begin(self) pen = QPen(Qt.black, 2, Qt.SolidLine) p.setPen(pen) p.drawLine(20, 15, 150, 15) pen.setStyle(Qt.DashLine) p.setPen(pen) p.drawLine(20, 35, 150, 35) pen.setStyle(Qt.DotLine) p.setPen(pen) p.drawLine(20, 55, 150, 55) pen.setStyle(Qt.DashDotLine) p.setPen(pen) p.drawLine(20, 75, 150, 75) pen.setStyle(Qt.DashDotDotLine) p.setPen(pen) p.drawLine(20, 95, 150, 95) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) p.setPen(pen) p.drawLine(20, 115, 150, 115) pen.setWidth(1) pen.setStyle(Qt.SolidLine) p.setPen(pen) brush = QBrush(Qt.SolidPattern) p.setBrush(brush) p.drawRect(180, 10, 40, 30) brush = QBrush(Qt.Dense5Pattern) p.setBrush(brush) p.drawRect(240, 10, 40, 30) brush = QBrush(Qt.Dense7Pattern) p.setBrush(brush) p.drawRect(300, 10, 40, 30) brush = QBrush(Qt.green, Qt.HorPattern) p.setBrush(brush) p.drawRect(180, 50, 40, 30) brush = QBrush(Qt.green, Qt.VerPattern) p.setBrush(brush) p.drawRect(240, 50, 40, 30) brush = QBrush(Qt.green, Qt.Dense6Pattern) brush = QBrush(Qt.green, Qt.CrossPattern) p.setBrush(brush) p.drawRect(300, 50, 40, 30) brush = QBrush(Qt.blue, Qt.BDiagPattern) p.setBrush(brush) p.drawRect(180, 90, 40, 30) brush = QBrush(Qt.blue, Qt.FDiagPattern) p.setBrush(brush) p.drawRect(240, 90, 40, 30) brush = QBrush(Qt.blue, Qt.DiagCrossPattern) p.setBrush(brush) p.drawRect(300, 90, 40, 30) g = QLinearGradient(180, 130, 220, 160) g.setColorAt(0, Qt.red) g.setColorAt(1, Qt.blue) brush = QBrush(g) p.setBrush(brush) p.drawRect(180, 130, 40, 30) g = QRadialGradient(260, 145, 20) g.setColorAt(0, Qt.red) g.setColorAt(0.5, Qt.yellow) g.setColorAt(1, Qt.blue) p.setBrush(g) p.drawRect(240, 130, 40, 30) g = QConicalGradient(320, 145, 0) g.setColorAt(0, Qt.red) g.setColorAt(0.4, Qt.yellow) g.setColorAt(0.8, Qt.blue) g.setColorAt(1, Qt.red) p.setBrush(g) p.drawRect(300, 130, 40, 30) brush = QBrush() brush.setTexture(QPixmap(":appres.img/texture.jpg")) p.setBrush(brush) pen.setColor(Qt.transparent) p.setPen(pen) p.drawRect(15, 130, 135, 35) p.end()
app = QApplication(sys.argv) __appname__ = "Red Network" ##################### importing the file made qt designer ##################### w = loadUi("Network_Gui.ui") #################### image for saving the picture of circles ################## img = QImage(w.widget.width(), w.widget.height(), QImage.Format_RGB32) img.fill(Qt.white) # image appears white in the beginning (not black) ################################ set imgpainter ############################### node_painter = QPainter() # painter for painting nodes imgpainter = QPainter() # painter for event_handler image ################################## set pen #################################### line_drawer = QPen() # pen for event_handler edges line_drawer.setWidth(4) ############################ set switch and lists ############################# switch = 0 # switch at 0 for first node, at 1 for second node edge_counter = 0 total_edge_length = 0 start_point_list = [0] end_point_list = [0] coordinate_set = set() midpoints = [] edges = []
class ShapeGUI(QGraphicsItem, Shape): PEN_NORMAL = QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine) PEN_NORMAL.setCosmetic(True) PEN_SELECT = QPen(QtCore.Qt.red, 2, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin) PEN_SELECT.setCosmetic(True) PEN_NORMAL_DISABLED = QPen(QtCore.Qt.gray, 1, QtCore.Qt.DotLine) PEN_NORMAL_DISABLED.setCosmetic(True) PEN_SELECT_DISABLED = QPen(QtCore.Qt.blue, 1, QtCore.Qt.DashLine) PEN_SELECT_DISABLED.setCosmetic(True) PEN_BREAK = QPen(QtCore.Qt.magenta, 1, QtCore.Qt.SolidLine) PEN_BREAK.setCosmetic(True) PEN_LEFT = QPen(QtCore.Qt.darkCyan, 1, QtCore.Qt.SolidLine) PEN_LEFT.setCosmetic(True) PEN_RIGHT = QPen(QtCore.Qt.darkMagenta, 1, QtCore.Qt.SolidLine) PEN_RIGHT.setCosmetic(True) def __init__(self, nr, closed, parentEntity): QGraphicsItem.__init__(self) Shape.__init__(self, nr, closed, parentEntity) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.selectionChangedCallback = None self.enableDisableCallback = None self.starrow = None self.enarrow = None def __str__(self): return super(ShapeGUI, self).__str__() def tr(self, string_to_translate): return super(ShapeGUI, self).tr(string_to_translate) def contains_point(self, point): """ Method to determine the minimal distance from the point to the shape @param point: a QPointF @return: minimal distance """ min_distance = float(0x7fffffff) ref_point = Point(point.x(), point.y()) t = 0.0 while t < 1.0: per_point = self.path.pointAtPercent(t) spline_point = Point(per_point.x(), per_point.y()) distance = ref_point.distance(spline_point) if distance < min_distance: min_distance = distance t += 0.01 return min_distance def setSelectionChangedCallback(self, callback): """ Register a callback function in order to inform parents when the selection has changed. Note: we can't use QT signals here because ShapeClass doesn't inherits from a QObject @param callback: the function to be called, with the prototype callbackFunction(shape, select) """ self.selectionChangedCallback = callback def setEnableDisableCallback(self, callback): """ Register a callback function in order to inform parents when a shape has been enabled or disabled. Note: we can't use QT signals here because ShapeClass doesn't inherits from a QObject @param callback: the function to be called, with the prototype callbackFunction(shape, enabled) """ self.enableDisableCallback = callback def setPen(self, pen): """ Method to change the Pen of the outline of the object and update the drawing """ self.pen = pen def paint(self, painter, option, widget): """ Method will be triggered with each paint event. Possible to give options @param painter: Reference to std. painter @param option: Possible options here @param widget: The widget which is painted on. """ if self.isSelected() and not self.isDisabled(): painter.setPen(ShapeGUI.PEN_SELECT) elif not self.isDisabled(): if self.parentLayer.isBreakLayer(): painter.setPen(ShapeGUI.PEN_BREAK) elif self.cut_cor == 41: painter.setPen(ShapeGUI.PEN_LEFT) elif self.cut_cor == 42: painter.setPen(ShapeGUI.PEN_RIGHT) else: painter.setPen(ShapeGUI.PEN_NORMAL) elif self.isSelected(): painter.setPen(ShapeGUI.PEN_SELECT_DISABLED) else: painter.setPen(ShapeGUI.PEN_NORMAL_DISABLED) painter.drawPath(self.path) def boundingRect(self): """ Required method for painting. Inherited by Painterpath @return: Gives the Bounding Box """ return self.path.boundingRect() def shape(self): """ Reimplemented function to select outline only. @return: Returns the Outline only """ painterStrock = QPainterPathStroker() painterStrock.setCurveThreshold(0.01) painterStrock.setWidth(0) stroke = painterStrock.createStroke(self.path) return stroke def setSelected(self, flag=True, blockSignals=True): """ Override inherited function to turn off selection of Arrows. @param flag: The flag to enable or disable Selection """ self.starrow.setSelected(flag) self.enarrow.setSelected(flag) self.stmove.setSelected(flag) QGraphicsItem.setSelected(self, flag) Shape.setSelected(self, flag) if self.selectionChangedCallback and not blockSignals: self.selectionChangedCallback(self, flag) def setDisable(self, flag=False, blockSignals=True): """ New implemented function which is in parallel to show and hide. @param flag: The flag to enable or disable Selection """ # QGraphicsItem.setDisable(self, flag) Shape.setDisable(self, flag) scene = self.scene() if scene is not None: if not scene.showDisabledPaths and flag: self.hide() self.starrow.setSelected(False) self.enarrow.setSelected(False) self.stmove.setSelected(False) else: self.show() if self.enableDisableCallback and not blockSignals: self.enableDisableCallback(self, not flag)