def generatePicture(self, data=None, redraw=False): """重新生成图形对象""" # 重画或者只更新最后一个K线 if redraw: self.pictures = [] elif self.pictures: self.pictures.pop() w = 0.4 bPen = self.bPen bBrush = self.bBrush rPen = self.rPen rBrush = self.rBrush self.low, self.high = (np.min(data['low']), np.max(data['high'])) if len(data) > 0 else (0, 1) npic = len(self.pictures) for (t, open0, close0, low0, high0) in data: if t >= npic: picture = QtGui.QPicture() p = QtGui.QPainter(picture) # 下跌蓝色(实心), 上涨红色(空心) pen,brush,pmin,pmax = (bPen,bBrush,close0,open0)\ if open0 > close0 else (rPen,rBrush,open0,close0) p.setPen(pen) p.setBrush(brush) # 画K线方块和上下影线 if open0 == close0: p.drawLine(QtCore.QPointF(t - w, open0), QtCore.QPointF(t + w, close0)) else: p.drawRect( QtCore.QRectF(t - w, open0, w * 2, close0 - open0)) if pmin > low0: p.drawLine(QtCore.QPointF(t, low0), QtCore.QPointF(t, pmin)) if high0 > pmax: p.drawLine(QtCore.QPointF(t, pmax), QtCore.QPointF(t, high0)) p.end() self.pictures.append(picture)
def __init__(self, parent, color, base_pt, camera, scalebox_dim): # get the base position in the plane base_pos = camera.spaceFromImage(base_pt, Z=0).T print("### base", base_pos, base_pt) # get the top position top_pos = base_pos + np.array([0, 0, scalebox_dim]) top_pt = camera.imageFromSpace(top_pos) print("### top", top_pos, top_pt) # get the left position left_pos = base_pos + np.array([scalebox_dim, 0, 0]) left_pt = camera.imageFromSpace(left_pos) print("### left", left_pos, left_pt) # get the back position back_pos = base_pos + np.array([0, scalebox_dim, 0]) back_pt = camera.imageFromSpace(back_pos) print("### back", back_pos, back_pt) ## draw element # set pen pen = QtGui.QPen(QtGui.QColor("#ff5f00")) pen.setWidth(5) pen.setCosmetic(True) # add object line_top = QtWidgets.QGraphicsLineItem( QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*top_pt))) line_left = QtWidgets.QGraphicsLineItem( QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*left_pt))) line_back = QtWidgets.QGraphicsLineItem( QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*back_pt))) self.lines = [line_top, line_left, line_back] _ = [line.setPen(pen) for line in self.lines] _ = [line.setParentItem(parent) for line in self.lines] _ = [line.setZValue(100) for line in self.lines]
def mouseReleaseEvent(self, event): self.grabCenter = False self.movingOffset = QtCore.QPointF(0, 0) self.update() self.moved.emit((0, 0))
def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" if QT5: pos = self.transformPos(ev.pos()) else: pos = self.transformPos(ev.posF()) self.prevMovePoint = pos self.restoreCursor() angleDeg = 0 # Polygon drawing. if self.drawing(): self.overrideCursor(CURSOR_DRAW) if not self.current: return color = self.lineColor if self.outOfPixmap(pos): # Don't allow the user to draw outside the pixmap. # Project the point to the pixmap's edges. pos = self.intersectionPoint(self.current[-1], pos) elif len(self.current) > 1 and \ self.closeEnough(pos, self.current[0]): # Attract line to starting point and # colorise to alert the user. pos = self.current[0] color = self.current.line_color self.overrideCursor(CURSOR_POINT) self.current.highlightVertex(0, Shape.NEAR_VERTEX) if self.createMode == 'polygon': self.line[0] = self.current[-1] self.line[1] = pos elif self.createMode == 'rectangle': self.line.points = list( self.getRectangleFromLine((self.current[0], pos))) self.line.close() elif self.createMode == 'line': self.line[0] = self.current[-1] self.line[1] = pos self.line.close() elif self.createMode == 'poses': self.line[0] = self.current[-1] self.line[1] = pos dx = self.line[1].x() - self.line[0].x() dy = self.line[1].y() - self.line[0].y() v_norm = math.sqrt(dx**2 + dy**2) distance = 50 point_on_line = [ self.line[0].x() + distance * dx / v_norm, self.line[0].y() + distance * dy / v_norm ] self.line[1] = QtCore.QPointF(point_on_line[0], point_on_line[1]) self.line.bnr_type = 'poses' else: raise ValueError self.line.line_color = color self.repaint() self.current.highlightClear() # Polygon copy moving. if QtCore.Qt.RightButton & ev.buttons(): if self.selectedShapeCopy and self.prevPoint: self.overrideCursor(CURSOR_MOVE) self.boundedMoveShape(self.selectedShapeCopy, pos) self.repaint() elif self.selectedShape: self.selectedShapeCopy = self.selectedShape.copy() self.repaint() self.cursorPos.emit(pos.x(), pos.y(), angleDeg) return # Polygon/Vertex moving. self.movingShape = False if QtCore.Qt.LeftButton & ev.buttons(): if self.selectedVertex(): self.boundedMoveVertex(pos) self.repaint() self.movingShape = True elif self.selectedShape and self.prevPoint: self.overrideCursor(CURSOR_MOVE) self.boundedMoveShape(self.selectedShape, pos) self.repaint() self.movingShape = True self.cursorPos.emit(pos.x(), pos.y(), angleDeg) return # Just hovering over the canvas, 2 posibilities: # - Highlight shapes # - Highlight vertex # Update shape/vertex fill and tooltip value accordingly. self.setToolTip("Image") for shape in reversed([s for s in self.shapes if self.isVisible(s)]): # Look for a nearby vertex to highlight. If that fails, # check if we happen to be inside a shape. index = shape.nearestVertex(pos, self.epsilon) index_edge = shape.nearestEdge(pos, self.epsilon) if index is not None: if self.selectedVertex(): self.hShape.highlightClear() self.hVertex = index self.hShape = shape self.hEdge = index_edge shape.highlightVertex(index, shape.MOVE_VERTEX) self.overrideCursor(CURSOR_POINT) self.setToolTip("Click & drag to move point") self.setStatusTip(self.toolTip()) self.update() break elif shape.containsPoint(pos) or index_edge is not None: if self.selectedVertex(): self.hShape.highlightClear() self.hVertex = None self.hShape = shape self.hEdge = index_edge self.setToolTip("Click & drag to move shape '%s'" % shape.label) self.setStatusTip(self.toolTip()) self.overrideCursor(CURSOR_GRAB) self.update() break else: # Nothing found, clear highlights, reset state. if self.hShape: self.hShape.highlightClear() self.update() self.hVertex, self.hShape, self.hEdge = None, None, None self.edgeSelected.emit(self.hEdge is not None) # Display angle if hover a poses if self.hShape: if self.hShape.bnr_type == 'poses': angleDeg = math.atan2( self.hShape.points[1].y() - self.hShape.points[0].y(), self.hShape.points[1].x() - self.hShape.points[0].x()) * 180 / math.pi if self.current: angleDeg = math.atan2( pos.y() - self.current[-1].y(), pos.x() - self.current[-1].x()) * 180 / math.pi self.cursorPos.emit(pos.x(), pos.y(), angleDeg)
def stop_resizing_polygon(self): if self.shape_type == "resizingshape": self.shape_type = "polygon" if self.last_inner_points is not None: self.points = [QtCore.QPointF(p[0], p[1]) for p in self.last_inner_points]
def paintEvent(self, QPaintEvent): real_size = min(self.width(), self.height()) painter = QtGui.QPainter(self) pen = QtGui.QPen(QtCore.Qt.black) pen.setWidth(1) painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.translate(self.width()/2, self.height()/2) painter.scale(real_size/self.scaledSize, real_size/self.scaledSize) gradient = QtGui.QRadialGradient(QtCore.QPointF(-500, -500), 1500, QtCore.QPointF(-500, -500)) gradient.setColorAt(0, QtGui.QColor(224, 224, 224)) gradient.setColorAt(1, QtGui.QColor(28, 28, 28)) painter.setPen(pen) painter.setBrush(QtGui.QBrush(gradient)) painter.drawEllipse(QtCore.QPointF(0, 0), 500, 500) gradient = QtGui.QRadialGradient(QtCore.QPointF(500, 500), 1500, QtCore.QPointF(500, 500)) gradient.setColorAt(0, QtGui.QColor(224, 224, 224)) gradient.setColorAt(1, QtGui.QColor(28, 28, 28)) painter.setPen(pen) painter.setBrush(QtGui.QBrush(gradient)) painter.drawEllipse(QtCore.QPointF(0, 0), 450, 450) painter.setPen(pen) if self.isChecked(): gradient = QtGui.QRadialGradient(QtCore.QPointF(-500, -500), 1500, QtCore.QPointF(-500, -500)) gradient.setColorAt(0, self.on_color_1) gradient.setColorAt(1, self.on_color_2) else: gradient = QtGui.QRadialGradient(QtCore.QPointF(500, 500), 1500, QtCore.QPointF(500, 500)) gradient.setColorAt(0, self.off_color_1) gradient.setColorAt(1, self.off_color_2) painter.setBrush(gradient) painter.drawEllipse(QtCore.QPointF(0, 0), 400, 400)
def set_size(self, x, y): temp_points = list(self.vertices) temp_points.append(QtCore.QPointF(x, y)) self.setPolygon(QtGui.QPolygonF(temp_points))
def update_scene_rect(self): pixmap = self.pixmap self.setSceneRect( QtCore.QRectF(QtCore.QPointF(0, 0), QtCore.QPointF(pixmap.width(), pixmap.height())))
def vectorize(self): v = QVector(QtCore.QPointF(0, 0), self.p2() - self.p1()) return v
class Crosshair(QtCore.QObject): """ 此类给pg.PlotWidget()添加crossHair功能,PlotWidget实例需要初始化时传入 """ signal = QtCore.pyqtSignal(type(tuple([]))) #---------------------------------------------------------------------- def __init__(self, parent, master): """Constructor""" self.__view = parent self.master = master super(Crosshair, self).__init__() self.xAxis = 0 self.yAxis = 0 self.datas = None self.yAxises = [0 for i in range(3)] self.leftX = [0 for i in range(3)] self.showHLine = [False for i in range(3)] self.textPrices = [pg.TextItem('', anchor=(1, 1)) for i in range(3)] self.views = [parent.centralWidget.getItem(i + 1, 0) for i in range(3)] self.rects = [self.views[i].sceneBoundingRect() for i in range(3)] self.vLines = [ pg.InfiniteLine(angle=90, movable=False) for i in range(3) ] self.hLines = [ pg.InfiniteLine(angle=0, movable=False) for i in range(3) ] #mid 在y轴动态跟随最新价显示最新价和最新时间 self.__textDate = pg.TextItem('date') self.__textInfo = pg.TextItem('lastBarInfo') self.__textSig = pg.TextItem('lastSigInfo', anchor=(1, 0)) self.__textIndicators = pg.TextItem('SAR', anchor=(1, 0)) self.__textVolume = pg.TextItem('lastBarVolume', anchor=(1, 0)) self.__textDate.setZValue(2) self.__textInfo.setZValue(2) self.__textSig.setZValue(2) self.__textVolume.setZValue(2) self.__textInfo.border = pg.mkPen(color=(230, 255, 0, 255), width=1.2) self.__textIndicators.setZValue(2) #指标 for i in range(3): self.textPrices[i].setZValue(2) self.vLines[i].setPos(0) self.hLines[i].setPos(0) self.views[i].addItem(self.vLines[i]) self.views[i].addItem(self.hLines[i]) self.views[i].addItem(self.textPrices[i]) self.views[0].addItem(self.__textInfo, ignoreBounds=True) self.views[0].addItem(self.__textSig, ignoreBounds=True) self.views[0].addItem(self.__textIndicators, ignoreBounds=True) self.views[1].addItem(self.__textVolume, ignoreBounds=True) self.views[2].addItem(self.__textDate, ignoreBounds=True) self.proxy = pg.SignalProxy(self.__view.scene().sigMouseMoved, rateLimit=60, slot=self.__mouseMoved) # 跨线程刷新界面支持 self.signal.connect(self.update) #---------------------------------------------------------------------- def update(self, pos): """刷新界面显示""" xAxis, yAxis = pos xAxis, yAxis = (self.xAxis, self.yAxis) if xAxis is None else (xAxis, yAxis) if self.datas is None: return self.moveTo(xAxis, yAxis) #---------------------------------------------------------------------- def __mouseMoved(self, evt): """鼠标移动回调""" if self.datas is None: return pos = evt[0] self.rects = [self.views[i].sceneBoundingRect() for i in range(3)] for i in range(3): self.showHLine[i] = False if self.rects[i].contains(pos): mousePoint = self.views[i].vb.mapSceneToView(pos) xAxis = mousePoint.x() yAxis = mousePoint.y() self.yAxises[i] = yAxis self.showHLine[i] = True self.moveTo(xAxis, yAxis) #---------------------------------------------------------------------- def moveTo(self, xAxis, yAxis): xAxis, yAxis = (self.xAxis, self.yAxis) if xAxis is None else (xAxis, yAxis) self.rects = [self.views[i].sceneBoundingRect() for i in range(3)] if not xAxis or not yAxis: return self.xAxis = xAxis self.yAxis = yAxis self.vhLinesSetXY(xAxis, yAxis) self.plotPrice(yAxis) self.plotInfo(xAxis) #---------------------------------------------------------------------- def vhLinesSetXY(self, xAxis, yAxis): """水平和竖线位置设置""" for i in range(3): self.vLines[i].setPos(xAxis) if self.showHLine[i]: self.hLines[i].setPos(yAxis if i == 0 else self.yAxises[i]) else: topLeft = self.views[i].vb.mapSceneToView( QtCore.QPointF(self.rects[i].left(), self.rects[i].top())) self.hLines[i].setPos(topLeft.y() + abs(topLeft.y())) #---------------------------------------------------------------------- def plotPrice(self, yAxis): """价格位置设置""" for i in range(3): if self.showHLine[i]: rightAxis = self.views[i].getAxis('right') rightAxisWidth = rightAxis.width() topRight = self.views[i].vb.mapSceneToView( QtCore.QPointF(self.rects[i].right() - rightAxisWidth, self.rects[i].top())) self.textPrices[i].setHtml( '<div style="text-align: right;">\ <span style="color: yellow; font-size: 12px;">\ %0.3f\ </span>\ </div>'\ % (yAxis if i==0 else self.yAxises[i])) self.textPrices[i].setPos(topRight.x(), yAxis if i == 0 else self.yAxises[i]) else: topRight = self.views[i].vb.mapSceneToView( QtCore.QPointF(self.rects[i].right(), self.rects[i].top())) self.textPrices[i].setPos(topRight.x(), topRight.y() + abs(topRight.y())) #---------------------------------------------------------------------- def plotInfo(self, xAxis): """ 被嵌入的plotWidget在需要的时候通过调用此方法显示K线信息 """ xAxis = round(xAxis) if self.datas is None: return try: # 获取K线数据 tickDatetime = self.datas[int(xAxis)]['datetime'] openPrice = self.datas[int(xAxis)]['open'] closePrice = self.datas[int(xAxis)]['close'] lowPrice = self.datas[int(xAxis)]['low'] highPrice = self.datas[int(xAxis)]['high'] volume = self.datas[int(xAxis)]['volume'] openInterest = self.datas[int(xAxis)]['openInterest'] preClosePrice = self.datas[int(xAxis) - 1]['close'] except Exception, e: return if (isinstance(tickDatetime, dt.datetime)): datetimeText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d %H:%M:%S') dateText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d') timeText = dt.datetime.strftime(tickDatetime, '%H:%M:%S') elif (isinstance(tickDatetime, (str))): datetimeText = tickDatetime dateTemp = dt.datetime.strptime(datetimeText, '%Y-%m-%d %H:%M:%S') dateText = dt.datetime.strftime(dateTemp, '%Y-%m-%d') timeText = dt.datetime.strftime(dateTemp, '%H:%M:%S') else: datetimeText = "" dateText = "" timeText = "" # 显示所有的主图技术指标 html = u'<div style="text-align: right">' for sig in self.master.sigData: val = self.master.sigData[sig][int(xAxis)] col = self.master.sigColor[sig] html += u'<span style="color: %s; font-size: 12px;"> %s:%.2f</span>' % ( col, sig, val) html += u'</div>' self.__textSig.setHtml(html) # 显示指标 if self.master.sarDatas is not None: # arrow=self.master.sars[int(xAxis)] self.__textIndicators.setHtml( '<div style="text-align: center">\ <span style="color: yellow; font-size: 12px;">SAR:%.2f</span>\ </div>'\ % (self.master.sarDatas[int(xAxis)])) # 和上一个收盘价比较,决定K线信息的字符颜色 openText = "%.3f" % openPrice closeText = "%.3f" % closePrice highText = "%.3f" % highPrice lowText = "%.3f" % lowPrice cOpen = 'red' if openPrice > preClosePrice else 'green' cClose = 'red' if closePrice > preClosePrice else 'green' cHigh = 'red' if highPrice > preClosePrice else 'green' cLow = 'red' if lowPrice > preClosePrice else 'green' self.__textInfo.setHtml( u'<div style="text-align: center; background-color:#000;height:auto ">\ <span style="color: white; font-size: 12px;">日期</span><br>\ <span style="color: yellow; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">时间</span><br>\ <span style="color: yellow; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">开盘</span><br>\ <span style="color: %s; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">最高</span><br>\ <span style="color: %s; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">最低</span><br>\ <span style="color: %s; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">收盘</span><br>\ <span style="color: %s; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">成交量</span><br>\ <span style="color: yellow; font-size: 12px;">%.3f</span><br>\ </div>'\ % (dateText,timeText,cOpen,openText,cHigh,highText,\ cLow,lowText,cClose,closeText,volume)) self.__textDate.setHtml( '<div style="text-align: center">\ <span style="color: yellow; font-size: 12px;">%s</span>\ </div>'\ % (datetimeText)) self.__textVolume.setHtml( '<div style="text-align: right">\ <span style="color: white; font-size: 12px;">VOL : %.3f</span>\ </div>'\ % (volume)) # K线子图,左上角显示 leftAxis = self.views[0].getAxis('left') leftAxisWidth = leftAxis.width() topLeft = self.views[0].vb.mapSceneToView( QtCore.QPointF(self.rects[0].left() + leftAxisWidth, self.rects[0].top())) x = topLeft.x() y = topLeft.y() self.__textInfo.setPos(x, y) # K线子图,左上角显示 leftAxis = self.views[0].getAxis('left') leftAxisWidth = leftAxis.width() topLeft = self.views[0].vb.mapSceneToView( QtCore.QPointF(self.rects[0].left() + leftAxisWidth, self.rects[0].top())) x = topLeft.x() y = topLeft.y() self.__textSig.setPos(x, y) # K线子图,右上角显示 rightAxis = self.views[0].getAxis('right') rightAxisWidth = rightAxis.width() topRight = self.views[0].vb.mapSceneToView( QtCore.QPointF(self.rects[0].right() - rightAxisWidth, self.rects[0].top())) x = topRight.x() y = topRight.y() self.__textIndicators.setPos(x, y) # 成交量子图,右上角显示 rightAxis = self.views[1].getAxis('right') rightAxisWidth = rightAxis.width() topRight = self.views[1].vb.mapSceneToView( QtCore.QPointF(self.rects[1].right() - rightAxisWidth, self.rects[1].top())) x = topRight.x() y = topRight.y() self.__textVolume.setPos(x, y) # X坐标时间显示 rectTextDate = self.__textDate.boundingRect() rectTextDateHeight = rectTextDate.height() bottomAxis = self.views[2].getAxis('bottom') bottomAxisHeight = bottomAxis.height() bottomRight = self.views[2].vb.mapSceneToView(QtCore.QPointF(self.rects[2].width(),\ self.rects[2].bottom()-(bottomAxisHeight+rectTextDateHeight))) # 修改对称方式防止遮挡 if xAxis > self.master.index: self.__textDate.anchor = Point((1, 0)) else: self.__textDate.anchor = Point((0, 0)) self.__textDate.setPos(xAxis, bottomRight.y())
def addNode(self): # NODE COLORS # text = 'Green = MESHES' node = Node(graph, "NODE COLOR ASSOCIATION") node.addPort( InputPort(node, graph, "GREEN = Meshes ", QtGui.QColor(243, 207, 139), 'MyDataX')) node.addPort( InputPort(node, graph, "PINK = Materials", QtGui.QColor(243, 207, 139), 'MyDataY')) node.addPort( InputPort(node, graph, "YELLOW = Cameras", QtGui.QColor(243, 207, 139), 'MyDataY')) node.addPort( InputPort(node, graph, "BLUE = SpotLights", QtGui.QColor(243, 207, 139), 'MyDataY')) node.setGraphPos(QtCore.QPointF(-250, 0)) node.setColor(QtGui.QColor(200, 200, 200, 255)) graph.addNode(node) text = fileContent.splitlines() lineList = [line.split() for line in text] myCamerasList = [] myMaterialsList = [] myMeshesList = [] mySpotLightsList = [] for line in lineList: # print line # GETS MESH NODES if line[0] == "createNode" and line[1] == "mesh": # print "My MESH Line" lineLength = len(line) - 1 meshNodeName = line[lineLength] meshNodeNameBroken = meshNodeName.split("\"") meshNodeNameClean = meshNodeNameBroken[1] myMeshesList.append(meshNodeNameClean) # GETS MATERIAL NODES elif line[0] == "createNode" and line[1] == "lambert": # print "My MAT Line" lineLength = len(line) - 1 matNodeName = line[lineLength] matNodeNameBroken = matNodeName.split("\"") matNodeNameClean = matNodeNameBroken[1] myMaterialsList.append(matNodeNameClean) # GETS CAMERA NODES elif line[0] == "createNode" and line[1] == "camera": # print "My MAT Line" lineLength = len(line) - 1 matNodeName = line[lineLength] matNodeNameBroken = matNodeName.split("\"") cameraNodeNameClean = matNodeNameBroken[1] myCamerasList.append(cameraNodeNameClean) # GETS SPOTLIGHT NODES elif line[0] == "createNode" and line[1] == "spotLight": # print "My MAT Line" lineLength = len(line) - 1 matNodeName = line[lineLength] matNodeNameBroken = matNodeName.split("\"") spotLightNodeNameClean = matNodeNameBroken[1] mySpotLightsList.append(spotLightNodeNameClean) # print myMeshesList x1 = len(myMeshesList) x2 = len(myMaterialsList) x3 = len(myCamerasList) x4 = len(mySpotLightsList) # print x # ADDIND NODE TYPES for meshNodeSpawn in range(x1): node = Node(graph, myMeshesList[meshNodeSpawn]) node.addPort( InputPort(node, graph, 'In ', QtGui.QColor(243, 207, 139), 'MyDataX')) node.addPort( OutputPort(node, graph, ' Out', QtGui.QColor(243, 207, 139), 'MyDataY')) node.setGraphPos(QtCore.QPointF(0, meshNodeSpawn * 80)) node.setColor(QtGui.QColor(92, 204, 146, 255)) graph.addNode(node) for materialNodeSpawn in range(x2): node = Node(graph, myMaterialsList[materialNodeSpawn]) node.addPort( InputPort(node, graph, 'In ', QtGui.QColor(243, 207, 139), 'MyDataX')) node.addPort( OutputPort(node, graph, ' Out', QtGui.QColor(243, 207, 139), 'MyDataY')) node.setGraphPos(QtCore.QPointF(150, materialNodeSpawn * 80)) node.setColor(QtGui.QColor(215, 140, 255, 255)) graph.addNode(node) for cameraNodeSpawn in range(x3): node = Node(graph, myCamerasList[cameraNodeSpawn]) node.addPort( InputPort(node, graph, 'In ', QtGui.QColor(243, 207, 139), 'MyDataX')) node.addPort( OutputPort(node, graph, ' Out', QtGui.QColor(243, 207, 139), 'MyDataY')) node.setGraphPos(QtCore.QPointF(300, cameraNodeSpawn * 80)) node.setColor(QtGui.QColor(243, 207, 139)) graph.addNode(node) for spotLightNodeSpawn in range(x4): node = Node(graph, mySpotLightsList[spotLightNodeSpawn]) node.addPort( InputPort(node, graph, 'In ', QtGui.QColor(243, 207, 139), 'MyDataX')) node.addPort( OutputPort(node, graph, ' Out', QtGui.QColor(243, 207, 139), 'MyDataY')) node.setGraphPos(QtCore.QPointF(450, spotLightNodeSpawn * 80)) node.setColor(QtGui.QColor(79, 170, 204, 255)) graph.addNode(node)
def __init__(self, parent=None): super(Joystick, self).__init__(parent) self.setMinimumSize(100, 100) self.movingOffset = QtCore.QPointF(0, 0) self.grabCenter = False self.__maxDistance = 40
def _center(self): return QtCore.QPointF(self.width() / 2, self.height() / 2)
def paintSection(self, painter, rect, logicalIndex): if not rect.isValid(): return painter.save() # get the state of the section opt = QtWidgets.QStyleOptionHeader() self.initStyleOption(opt) state = QtWidgets.QStyle.State_None if self.isEnabled(): state |= QtWidgets.QStyle.State_Enabled if self.window().isActiveWindow(): state |= QtWidgets.QStyle.State_Active # store some frequently used objects setOptBrush = opt.palette.setBrush getHeaderData = self.model().headerData palette = self.palette() orientation = self.orientation() # set up sorted column headers sortColumns = self.model().sorter.sortColumns sortDirections = self.model().sorter.sortDirections sortIndex = -1 if self.isSortIndicatorShown(): try: sortIndex = sortColumns.index(logicalIndex) except ValueError: pass # this column is not a part of the multi-sort if sortIndex >= 0: opt.sortIndicator = QtWidgets.QStyleOptionHeader.SortDown if sortDirections[ sortIndex] == QtCore.Qt.AscendingOrder else QtWidgets.QStyleOptionHeader.SortUp # paint sorted column slightly darker than normal setOptBrush(QtGui.QPalette.Button, QtGui.QBrush(palette.button().color().darker(110))) setOptBrush(QtGui.QPalette.Window, QtGui.QBrush(palette.window().color().darker(110))) setOptBrush(QtGui.QPalette.Dark, QtGui.QBrush(palette.dark().color().darker(110))) # setup the style options structure opt.rect = rect opt.section = logicalIndex opt.state |= state opt.text = getHeaderData(logicalIndex, orientation, QtCore.Qt.DisplayRole) textAlignment = getHeaderData(logicalIndex, orientation, QtCore.Qt.TextAlignmentRole) opt.textAlignment = QtCore.Qt.Alignment( textAlignment if textAlignment is not None else self. defaultAlignment()) opt.iconAlignment = QtCore.Qt.AlignVCenter if self.textElideMode() != QtCore.Qt.ElideNone: opt.text = opt.fontMetrics.elidedText(opt.text, self.textElideMode(), rect.width() - 4) icon = getHeaderData(logicalIndex, orientation, QtCore.Qt.DecorationRole) if icon: opt.icon = icon foregroundBrush = getHeaderData(logicalIndex, orientation, QtCore.Qt.ForegroundRole) if foregroundBrush: setOptBrush(QtGui.QPalette.ButtonText, foregroundBrush) backgroundBrush = getHeaderData(logicalIndex, orientation, QtCore.Qt.BackgroundRole) if backgroundBrush: setOptBrush(QtGui.QPalette.Button, backgroundBrush) setOptBrush(QtGui.QPalette.Window, backgroundBrush) painter.setBrushOrigin(opt.rect.topLeft()) # determine column position visual = self.visualIndex(logicalIndex) assert visual != -1 if self.count() == 1: opt.position = QtWidgets.QStyleOptionHeader.OnlyOneSection elif visual == 0: opt.position = QtWidgets.QStyleOptionHeader.Beginning elif visual == self.count() - 1: opt.position = QtWidgets.QStyleOptionHeader.End else: opt.position = QtWidgets.QStyleOptionHeader.Middle opt.orientation = orientation # draw the section self.style().drawControl(QtWidgets.QStyle.CE_Header, opt, painter, self) painter.restore() # darken if it is a locked column in the view if not self.__columnIsUnlocked(logicalIndex): painter.fillRect(rect, QtGui.QColor(0, 0, 0, 40)) # paint a number overlay when multi-sorting if sortIndex >= 0 and len(sortColumns) > 1: # paint a number indicator when multi-sorting text = str(sortIndex + 1) headerFont = QtGui.QFont(painter.font()) headerFont.setPointSize(headerFont.pointSize() - 2) textWidth = QtGui.QFontMetrics(headerFont).boundingRect( text).width() # calculate the indicator location point = QtCore.QPointF(rect.bottomRight()) point.setX(point.x() - textWidth - 1) point.setY(point.y() - 1) # paint the number overlay painter.save() painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source) painter.setFont(headerFont) painter.drawText(point, text) painter.restore()
def drawStations(self, qp): stn_xs, stn_ys = self.mapper(self.stn_lats, self.stn_lons + self.map_rot) lb_lat, ub_lat = self.mapper.getLatBounds() size = 3 * self.scale # JTS - Apply QC coloring to NUCAPS. if self.cur_source.getName().startswith("NUCAPS"): unselected_color_nucaps = QtCore.Qt.red selected_color_nucaps = QtCore.Qt.green window_rect = QtCore.QRect(0, 0, self.width(), self.height()) clicked_x, clicked_y, clicked_lat, clicked_id = None, None, None, None for stn_x, stn_y, stn_lat, stn_id, stn_qc_flag in zip(stn_xs, stn_ys, self.stn_lats, self.stn_ids, self.stn_qc_flags): if self.clicked_stn == stn_id: clicked_x = stn_x clicked_y = stn_y clicked_lat = stn_lat clicked_id = stn_id else: if stn_qc_flag == 'green': unselected_color_nucaps = QtCore.Qt.darkGreen elif stn_qc_flag == 'yellow': unselected_color_nucaps = QtCore.Qt.yellow elif stn_qc_flag == 'red': unselected_color_nucaps = QtCore.Qt.red else: unselected_color_nucaps = QtCore.Qt.white if lb_lat <= stn_lat and stn_lat <= ub_lat and window_rect.contains(*self.transform.map(stn_x, stn_y)): qp.setPen(QtGui.QPen(unselected_color_nucaps, self.scale)) qp.setBrush(QtGui.QBrush(unselected_color_nucaps)) qp.drawEllipse(QtCore.QPointF(stn_x, stn_y), size, size) if clicked_lat is not None and lb_lat <= clicked_lat and clicked_lat <= ub_lat and window_rect.contains(*self.transform.map(clicked_x, clicked_y)): qp.setPen(QtGui.QPen(selected_color_nucaps, self.scale)) qp.setBrush(QtGui.QBrush(selected_color_nucaps)) qp.drawEllipse(QtCore.QPointF(clicked_x, clicked_y), size, size) else: # JTS - Non-NUCAPS data will not have the QC coloring applied. unselected_color = QtCore.Qt.red selected_color = QtCore.Qt.green window_rect = QtCore.QRect(0, 0, self.width(), self.height()) clicked_x, clicked_y, clicked_lat, clicked_id = None, None, None, None color = unselected_color for stn_x, stn_y, stn_lat, stn_id in zip(stn_xs, stn_ys, self.stn_lats, self.stn_ids): if self.clicked_stn == stn_id: clicked_x = stn_x clicked_y = stn_y clicked_lat = stn_lat clicked_id = stn_id else: if lb_lat <= stn_lat and stn_lat <= ub_lat and window_rect.contains(*self.transform.map(stn_x, stn_y)): qp.setPen(QtGui.QPen(color, self.scale)) qp.setBrush(QtGui.QBrush(color)) qp.drawEllipse(QtCore.QPointF(stn_x, stn_y), size, size) color = selected_color if clicked_lat is not None and lb_lat <= clicked_lat and clicked_lat <= ub_lat and window_rect.contains(*self.transform.map(clicked_x, clicked_y)): qp.setPen(QtGui.QPen(color, self.scale)) qp.setBrush(QtGui.QBrush(color)) qp.drawEllipse(QtCore.QPointF(clicked_x, clicked_y), size, size) if self.cur_source.getName() == "Local WRF-ARW" and self.pt_x != None: qp.drawEllipse(QtCore.QPointF(self.pt_x, self.pt_y), size, size)
def _ports_updated(self, ports_removed, ports_added, edges_removed, edges_added): self.port_map = self.monitor.port_map for src, dest in edges_removed: try: src_info = self._nodes[src] dest_info = self._nodes[dest] except KeyError: logger.error('Edge removed that did not connect a known port, ' 'likely in error: %s -> %s', src, dest) continue src_node = src_info['node'] dest_node = dest_info['node'] conn = src_info['connections'].pop(dest, None) dest_info['connections'].pop(src, None) if conn is None: logger.debug('No connection found between %s -> %s', src, dest) else: self._edges_removed.append((src, dest)) self.scene.delete_connection(conn) self._edges.remove((src, dest)) for port in ports_removed: node = self._nodes.pop(port) self.scene.remove_node(node) for port in ports_added: plugin = self.port_map[port] self._nodes[port] = dict(node=self.add_port(port, plugin), plugin=plugin, connections={}, ) first_update = not self._edges for src, dest in edges_added: try: src_node = self._nodes[src]['node'] dest_node = self._nodes[dest]['node'] except KeyError: # Scenarios: # 1. Invalid port name used # 2. Associated plugin missing from the Detector class logger.debug('Edge added to unknown port: %s -> %s', src, dest) continue if src_node == dest_node: logger.debug('Cycle with node %s?', src_node) continue self._edges.add((src, dest)) try: connection = self._connected_by_user.pop((src, dest), None) if connection is None: connection = self.scene.create_connection( src_node['output'][0], dest_node['input'][0], ) except Exception: logger.exception('Failed to connect terminals %s -> %s', src, dest) else: self._nodes[src]['connections'][dest] = connection self._nodes[dest]['connections'][src] = connection if self._auto_position or first_update: x_spacing = 150.0 # TODO less magic numbers y_spacing = 100.0 positions = utils.position_nodes( self._edges, self.port_map, x_spacing=x_spacing, y_spacing=y_spacing, ) for port, (px, py) in positions.items(): node = self._nodes[port]['node'] node.graphics_object.setPos(QtCore.QPointF(px, py)) if first_update: # on the first update, ensure that the scene rectangle is set # to fit all nodes x_positions = [px for px, py in positions.values()] y_positions = [py for px, py in positions.values()] min_x, max_x = min(x_positions), max(x_positions) min_y, max_y = min(y_positions), max(y_positions) scene_rect = QtCore.QRectF(min_x - x_spacing, min_y - y_spacing, max_x - min_x + x_spacing, max_y - min_y + y_spacing) self.view.setSceneRect(scene_rect) self.view.fitInView(scene_rect, QtCore.Qt.KeepAspectRatio) self.flowchart_updated.emit()
def growShape(self): im = self.image.convertToFormat(QtGui.QImage.Format_RGB888) width = im.width() height = im.height() ptr = im.constBits() ptr.setsize(height * width * 3) np_img = np.array(ptr, dtype=np.uint8).reshape(height, width, 3) cv2.imwrite('/tmp/bus.jpg', np_img) contour = None for shapenum, shape in enumerate(self.selectedShapes): #contour=shape. try: mask = np.ones(np_img.shape[:2], dtype=np.uint8) * cv2.GC_PR_BGD mask1 = np.zeros(np_img.shape[:2], dtype=np.uint8) testcontour = [] if (shape.shape_type == 'polygon'): contour = shape.getNpPath() cv2.fillPoly(mask1, pts=[np.array(contour, dtype=np.int32)], color=(255, 255, 255)) testcontour = contour elif (shape.shape_type == 'rectangle'): line = shape.getNpPath() print("Rectangle line:", line) #contour=line[0], cv2.fillPoly(mask1, contour, color=(255, 255, 255)) testcontour = contour elif (shape.shape_type == 'circle'): #cv2.fillEllipse() ##??? pass except Exception as e: #import code #code.interact(local=locals()) print("Exception:", e) print("img:", np_img.shape) print(contour) mask[mask1 == 255] = cv2.GC_FGD bgdmodel = np.zeros((1, 65), np.float64) fgdmodel = np.zeros((1, 65), np.float64) cv2.grabCut(np_img, mask, (0, 0, width, height), bgdmodel, fgdmodel, 1, cv2.GC_INIT_WITH_MASK) mask3 = np.where((mask == 1) + (mask == 3), 255, 0).astype(np.uint8) contours, hierarchy = cv2.findContours(mask3, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1) for cont in contours: flag = True for p in testcontour: if cv2.pointPolygonTest(cont, tuple(p), True) < 0: flag = False if flag: #cv2.drawContours(np_img,[cont],0,(255,0,0),2) #cv2.imwrite('/tmp/contours.jpg',np_img) ## Simplify contour curve_len = cv2.arcLength(cont, True) new_contour = cv2.approxPolyDP(cont, 0.002 * curve_len, True) new_shape = Shape(label=shape.label, shape_type='polygon') for point in new_contour: print("Point=", point) x, y = tuple(point[0]) new_shape.addPoint(QtCore.QPointF(x, y)) if (shape.line_color): new_shape.line_color = shape.line_color new_shape.close() self.selectedShapesCopy.append(new_shape) break if (not flag): # We found no good contour self.selectedShapesCopy.append(self.selectedShapes[shapenum]) self.endMove(copy=False)
def getGraphPos(self): transform = self.transform() size = self.size() return QtCore.QPointF(transform.dx() + (size.width() * 0.5), transform.dy() + (size.height() * 0.5))
def limitRefreshRange(self): self.range = QtCore.QRectF() self.range.setWidth((self.width() + 20) / self.scale[0]) self.range.setHeight((self.height() + 20) / self.scale[1]) self.range.moveCenter(QtCore.QPointF(*self.center)) self.setSceneRect(self.range)
def load_label(self, output_dir): self.labels = [LabelFile() for _ in range(self.shape[0])] if output_dir is None or not osp.exists(output_dir): return if self.dimension == 2: # 那么标签是一个文件 labelf_name = self.stripext(self.image_name) + LabelFile.suffix labelf_path = osp.join(output_dir, labelf_name) print("labelf_path", labelf_path) if not osp.exists(labelf_path) or LabelFile.is_label_file( labelf_path): return # TODO: 主调处理 LabelFileError self.labels[0] = LabelFile(labelf_path) self.label_path = labelf_path else: output_dir = osp.join(output_dir, self.stripext(self.image_name)) if not osp.exists(output_dir): return self.label_path = output_dir labelf_names = [ n for n in os.listdir(output_dir) if n.endswith(LabelFile.suffix) ] print("Found label files", labelf_names) labelf_names.sort() for idx, name in enumerate(labelf_names): # TODO: 这里初步根据文件名确定下标,后期改成3djson里写下标 self.labels[idx] = LabelFile(osp.join(output_dir, name)) for idx in range(len(self.labels)): s = [] for shape in self.labels[idx].shapes: label = shape["label"] points = shape["points"] shape_type = shape["shape_type"] flags = shape["flags"] group_id = shape["group_id"] other_data = shape["other_data"] # skip point-empty shape if not points: continue shape = Shape( label=label, shape_type=shape_type, group_id=group_id, ) for x, y in points: shape.addPoint(QtCore.QPointF(x, y)) shape.close() default_flags = {} # if self._config["label_flags"]: # for pattern, keys in self._config["label_flags"].items(): # if re.match(pattern, label): # for key in keys: # default_flags[key] = False shape.flags = default_flags shape.flags.update(flags) shape.other_data = other_data s.append(shape) self.labels[idx].shapes = s
node1.addPort( InputPort(node1, graph, 'InPort1', QtGui.QColor(128, 170, 170, 255), 'MyDataX')) node1.addPort( InputPort(node1, graph, 'InPort2', QtGui.QColor(128, 170, 170, 255), 'MyDataX')) node1.addPort( OutputPort(node1, graph, 'OutPort', QtGui.QColor(32, 255, 32, 255), 'MyDataY')) node1.addPort( IOPort(node1, graph, 'IOPort1', QtGui.QColor(32, 255, 32, 255), 'MyDataY')) node1.addPort( IOPort(node1, graph, 'IOPort2', QtGui.QColor(32, 255, 32, 255), 'MyDataY')) node1.setGraphPos(QtCore.QPointF(-100, 0)) graph.addNode(node1) node2 = Node(graph, 'ReallyLongLabel') node2.addPort( InputPort(node2, graph, 'InPort1', QtGui.QColor(128, 170, 170, 255), 'MyDataX')) node2.addPort( InputPort(node2, graph, 'InPort2', QtGui.QColor(128, 170, 170, 255), 'MyDataX')) node2.addPort( OutputPort(node2, graph, 'OutPort', QtGui.QColor(32, 255, 32, 255), 'MyDataY')) node2.addPort( IOPort(node2, graph, 'IOPort1', QtGui.QColor(32, 255, 32, 255),
def plotInfo(self, xAxis, yAxis): """ 被嵌入的plotWidget在需要的时候通过调用此方法显示K线信息 """ if self.datas is None: return try: # 获取K线数据 data = self.datas[xAxis] lastdata = self.datas[xAxis - 1] tickDatetime = data['datetime'] openPrice = data['open'] closePrice = data['close'] lowPrice = data['low'] highPrice = data['high'] volume = int(data['volume']) openInterest = int(data['openInterest']) preClosePrice = lastdata['close'] MA_S = 0 if len(self.ma_s_values) > 0 and self.master.MA_SHORT_show == True: MA_S = self.ma_s_values[xAxis] MA_L = 0 if len(self.ma_l_values) > 0 and self.master.MA_LONG_show == True: MA_L = self.ma_l_values[xAxis] tradePrice = 0 if cmp(self.master.listSig_deal_DIRECTION[xAxis], '-') == 0 or cmp( self.master.listSig_deal_OFFSET[xAxis], '-') == 0: tradePrice = 0 else: tradePrice = closePrice # 所有策略以收盘价成交 except Exception as e: return if (isinstance(tickDatetime, dt.datetime)): datetimeText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d %H:%M:%S') dateText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d') timeText = dt.datetime.strftime(tickDatetime, '%H:%M:%S') else: ''' datetimeText = "" dateText = "" timeText = "" ''' datetimeText = dt.datetime.strftime( pd.to_datetime(pd.to_datetime(tickDatetime)), '%Y-%m-%d %H:%M:%S') dateText = dt.datetime.strftime( pd.to_datetime(pd.to_datetime(tickDatetime)), '%Y-%m-%d') timeText = dt.datetime.strftime( pd.to_datetime(pd.to_datetime(tickDatetime)), '%H:%M:%S') # 显示所有的主图技术指标 html = u'<div style="text-align: right">' for sig in self.master.sigData: val = self.master.sigData[sig][xAxis] col = self.master.sigColor[sig] html += u'<span style="color: %s; font-size: 12px;"> %s:%.2f</span>' % ( col, sig, val) html += u'</div>' self.__textSig.setHtml(html) # 显示所有的主图技术指标 html = u'<div style="text-align: right">' for sig in self.master.subSigData: val = self.master.subSigData[sig][xAxis] col = self.master.subSigColor[sig] html += u'<span style="color: %s; font-size: 12px;"> %s:%.2f</span>' % ( col, sig, val) html += u'</div>' self.__textSubSig.setHtml(html) # 和上一个收盘价比较,决定K线信息的字符颜色 cOpen = 'red' if openPrice > preClosePrice else 'green' cClose = 'red' if closePrice > preClosePrice else 'green' cHigh = 'red' if highPrice > preClosePrice else 'green' cLow = 'red' if lowPrice > preClosePrice else 'green' self.__textInfo.setHtml( u'<div style="text-align: center; background-color:#000">\ <span style="color: white; font-size: 12px;">日期</span><br>\ <span style="color: yellow; font-size: 12px;">%s</span><br>\ <span style="color: white; font-size: 12px;">价格</span><br>\ <span style="color: %s; font-size: 12px;">(开) %d</span><br>\ <span style="color: %s; font-size: 12px;">(高) %d</span><br>\ <span style="color: %s; font-size: 12px;">(低) %d</span><br>\ <span style="color: %s; font-size: 12px;">(收) %d</span><br>\ <span style="color: white; font-size: 12px;">成交价</span><br>\ <span style="color: yellow; font-size: 12px;">(价) %d</span><br>\ <span style="color: white; font-size: 12px;">指标</span><br>\ <span style="color: yellow; font-size: 12px;">(MAS) %d</span><br>\ <span style="color: yellow; font-size: 12px;">(MAL) %d</span><br>\ </div>'\ % (dateText,cOpen,openPrice,cHigh,highPrice,\ cLow,lowPrice,cClose,closePrice,tradePrice,MA_S,MA_L)) self.__textDate.setHtml( '<div style="text-align: center">\ <span style="color: yellow; font-size: 12px;">%s</span>\ </div>'\ % (dateText)) self.__textVolume.setHtml( '<div style="text-align: right">\ <span style="color: white; font-size: 12px;">VOL : %d</span>\ </div>'\ % (volume)) # 坐标轴宽度 rightAxisWidth = self.views[0].getAxis('right').width() bottomAxisHeight = self.views[2].getAxis('bottom').height() offset = QtCore.QPointF(rightAxisWidth, bottomAxisHeight) # 各个顶点 tl = [ self.views[i].vb.mapSceneToView(self.rects[i].topLeft()) for i in range(3) ] br = [ self.views[i].vb.mapSceneToView(self.rects[i].bottomRight() - offset) for i in range(3) ] # 显示价格 for i in range(3): if self.showHLine[i]: self.textPrices[i].setHtml( '<div style="text-align: right">\ <span style="color: yellow; font-size: 12px;">\ %d\ </span>\ </div>'\ % (yAxis if i==0 else self.yAxises[i])) self.textPrices[i].setPos(br[i].x(), yAxis if i == 0 else self.yAxises[i]) self.textPrices[i].show() else: self.textPrices[i].hide() # 设置坐标 self.__textInfo.setPos(tl[0]) self.__textSig.setPos(br[0].x(), tl[0].y()) self.__textSubSig.setPos(br[2].x(), tl[2].y()) self.__textVolume.setPos(br[1].x(), tl[1].y()) # 修改对称方式防止遮挡 self.__textDate.anchor = Point( (1, 1)) if xAxis > self.master.index else Point((0, 1)) self.__textDate.setPos(xAxis, br[2].y())
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.anchor = QtCore.QPointF() self.text = None self.text_rect = None self.font = gui.Font()
def mapToGalvo(self, pt): '''maps a scene point to a percent to be used in the galvo driver''' p = QtCore.QPointF(self.views()[0].mapFromScene(pt)) p.setX(p.x() / self.views()[0].width()) p.setY(p.y() / self.views()[0].height()) return p
def translate_to(self, point=QtCore.QPointF(0, 0)): vec = self + QVector(self.p1(), point) return vec
def mapFromPercent(self, p): p = [ self.boundRect.x() + (p.x() * self.boundRect.width()), self.boundRect.y() + (p.y() * self.boundRect.height()) ] return QtCore.QPointF(max(-10, min(p[0], 10)), max(-10, min(p[1], 10)))
def add_point(self, x, y): self.vertices.append(QtCore.QPointF(x, y)) self.setPolygon(QtGui.QPolygonF(self.vertices))
def plotInfo(self, xAxis, yAxis): """ 被嵌入的plotWidget在需要的时候通过调用此方法显示K线信息 """ if self.datas is None: return try: # 获取K线数据 data = self.datas[xAxis] lastdata = self.datas[xAxis - 1] tickDatetime = data['datetime'] openPrice = data['open'] closePrice = data['close'] lowPrice = data['low'] highPrice = data['high'] # volume = int(data['volume']) # openInterest = int(data['openInterest']) preClosePrice = lastdata['close'] # tradePrice = abs(self.master.listSig[xAxis][1]) sig = np.array(self.master.listSig) index = np.where(sig[:, 0] == str(xAxis)) if len(list(index)[0]) > 0: tradePrice = float(sig[index[0]][0][1]) else: tradePrice = 0 except Exception as e: return if (isinstance(tickDatetime, dt.datetime)): datetimeText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d %H:%M:%S') dateText = dt.datetime.strftime(tickDatetime, '%Y-%m-%d') timeText = dt.datetime.strftime(tickDatetime, '%H:%M:%S') else: datetimeText = "" dateText = "" timeText = "" # 显示所有的主图技术指标 html = u'<div style="text-align: right">' for sig in sorted(self.master.sigData, key=lambda x: int(x[2:])): val = self.master.sigData[sig][xAxis] col = self.master.sigColor[sig] html += u'<span style="color: %s; font-size: 18px;"> %s:%.2f</span>' % ( col, sig, val) html += u'</div>' self.__textSig.setHtml(html) # 显示所有的主图技术指标 html = u'<div style="text-align: right">' for sig in self.master.subSigData: val = self.master.subSigData[sig][xAxis] col = self.master.subSigColor[sig] html += u'<span style="color: %s; font-size: 18px;"> %s:%.2f</span>' % ( col, sig, val) html += u'</div>' self.__textSubSig.setHtml(html) # 和上一个收盘价比较,决定K线信息的字符颜色 cOpen = 'red' if openPrice > preClosePrice else 'green' cClose = 'red' if closePrice > preClosePrice else 'green' cHigh = 'red' if highPrice > preClosePrice else 'green' cLow = 'red' if lowPrice > preClosePrice else 'green' self.__textInfo.setHtml( u'<div style="text-align: center; background-color:#000">\ <span style="color: white; font-size: 16px;">日期</span><br>\ <span style="color: yellow; font-size: 16px;">%s</span><br>\ <span style="color: white; font-size: 16px;">时间</span><br>\ <span style="color: yellow; font-size: 16px;">%s</span><br>\ <span style="color: white; font-size: 16px;">价格</span><br>\ <span style="color: %s; font-size: 16px;">(开) %.3f</span><br>\ <span style="color: %s; font-size: 16px;">(高) %.3f</span><br>\ <span style="color: %s; font-size: 16px;">(低) %.3f</span><br>\ <span style="color: %s; font-size: 16px;">(收) %.3f</span><br>\ <span style="color: white; font-size: 16px;">成交量</span><br>\ <span style="color: yellow; font-size: 16px;">(量) %d</span><br>\ <span style="color: white; font-size: 16px;">成交价</span><br>\ <span style="color: yellow; font-size: 16px;">(价) %.3f</span><br>\ </div>' % (dateText, timeText, cOpen, openPrice, cHigh, highPrice, cLow, lowPrice, cClose, closePrice, 0, tradePrice)) self.__textDate.setHtml( '<div style="text-align: center">\ <span style="color: yellow; font-size: 18px;">%s</span>\ </div>'\ % (datetimeText)) self.__textVolume.setHtml( '<div style="text-align: right">\ <span style="color: white; font-size: 18px;">VOL : %.3f</span>\ </div>'\ % (0)) # 坐标轴宽度 rightAxisWidth = self.views[0].getAxis('right').width() bottomAxisHeight = self.views[2].getAxis('bottom').height() offset = QtCore.QPointF(rightAxisWidth, bottomAxisHeight) # 各个顶点 tl = [ self.views[i].vb.mapSceneToView(self.rects[i].topLeft()) for i in range(3) ] br = [ self.views[i].vb.mapSceneToView(self.rects[i].bottomRight() - offset) for i in range(3) ] # 显示价格 for i in range(3): if self.showHLine[i]: self.textPrices[i].setHtml( '<div style="text-align: right">\ <span style="color: yellow; font-size: 18px;">\ %0.3f\ </span>\ </div>'\ % (yAxis if i==0 else self.yAxises[i])) self.textPrices[i].setPos(br[i].x(), yAxis if i == 0 else self.yAxises[i]) self.textPrices[i].show() else: self.textPrices[i].hide() # 设置坐标 # self.__textInfo.setPos(tl[0]) self.__textSig.setPos(br[0].x(), tl[0].y()) # self.__textSubSig.setPos(br[2].x(),tl[2].y()) # self.__textVolume.setPos(br[1].x(),tl[1].y()) # 修改对称方式防止遮挡 # offset2 = QtCore.QPointF(20, 20) r = self.__textSig.boundingRect() offset2 = self.__textSig.mapToParent(r.bottomRight()).y() if xAxis > self.master.index: self.__textInfo.setPos(tl[0].x(), offset2) self.__textInfo.anchor = Point((0, 0)) else: self.__textInfo.anchor = Point((1, 0)) self.__textInfo.setPos(br[0].x(), offset2) self.__textDate.anchor = Point( (1, 1)) if xAxis > self.master.index else Point((0, 1)) self.__textDate.setPos(xAxis, br[2].y())
def add_point(self, x, y): self.vertices.append(QtCore.QPointF(x, y))
def stop_resizing_basicshape(self): self.shape_type = "polygon" self.resizing_box_points = self.points self.points = [QtCore.QPointF(p[0], p[1]) for p in self.last_inner_points]