def slot_canvasSaveImage(self): newPath = QFileDialog.getSaveFileName( self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)")) if not newPath: return self.scene.clearSelection() if newPath.lower().endswith(".jpg"): imgFormat = "JPG" elif newPath.lower().endswith(".png"): imgFormat = "PNG" else: # File-dialog may not auto-add the extension imgFormat = "PNG" newPath += ".png" self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32) painter = QPainter(self.fExportImage) painter.save() painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) self.scene.render(painter) self.fExportImage.save(newPath, imgFormat, 100) painter.restore()
def paintEvent(self, event): painter=QPainter(self) angleSpan = self.m_endAngle - self.m_startAngle valueSpan = self.m_maximum - self.m_minimum rotate = (self.m_value - self.m_minimum) / valueSpan * angleSpan + self.m_startAngle targetRect = self.availableRect(self.m_backgroundRenderer) painter.translate((self.width() - targetRect.width()) / 2.0, (self.height() - targetRect.height()) / 2.0) painter.save() self.m_backgroundRenderer.render(painter, targetRect) targetRect = self.availableRect(self.m_needleRenderer) targetRect.moveTopLeft(QPointF(-targetRect.width() * self.m_originX, -targetRect.height() * self.m_originY)) painter.translate(targetRect.width() * self.m_originX, targetRect.height() * self.m_originY) painter.save() painter.translate(2, 4) painter.rotate(rotate) self.m_needleShadowRenderer.render(painter, targetRect) painter.restore() painter.rotate(rotate) self.m_needleRenderer.render(painter, targetRect) painter.restore(); if self.m_showOverlay: targetRect = self.availableRect(self.m_overlayRenderer) self.m_overlayRenderer.render(painter, targetRect)
def paintEvent(self, event=None): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) xOffset = self.width() / SIZE yOffset = self.height() / SIZE for x in range(SIZE): for y in range(SIZE): cell = self.grid[x][y] rect = (QRectF(x * xOffset, y * yOffset, xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5)) great_rect = QRectF(x * xOffset, y * yOffset, xOffset, yOffset) if cell != BLANK: painter.save() painter.setPen(Qt.black) font = QFont() font.setPointSize(20) painter.setFont(font) painter.drawText(rect, Qt.AlignCenter, cell) painter.restore() if [x, y] == self.selected: painter.setPen(QPen(Qt.blue, SIZE)) else: painter.setPen(Qt.black) painter.drawRect(rect)
def slot_canvasSaveImage(self): newPath = QFileDialog.getSaveFileName( self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)") ) if not newPath: return self.scene.clearSelection() if newPath.lower().endswith(".jpg"): imgFormat = "JPG" elif newPath.lower().endswith(".png"): imgFormat = "PNG" else: # File-dialog may not auto-add the extension imgFormat = "PNG" newPath += ".png" self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32) painter = QPainter(self.fExportImage) painter.save() painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) self.scene.render(painter) self.fExportImage.save(newPath, imgFormat, 100) painter.restore()
def paintEvent(self, event): painter = QPainter() painter.begin(self) if not self.showRegionMap: painter.drawPixmap(0, 0, self.scaledOwnershipMap) rect = self.imageRect() if self.isEnabled(): if self.showRegionMap: painter.drawPixmap(0, 0, self.scaledRegionMap) else: if self.currentTerritory: painter.drawPixmap(0, 0, self.coloredMask(self.currentTerritory, QColor(*self.game.clientPlayer.color))) #draw active animations for a in self.animations: painter.save() a.paint(painter) painter.restore() painter.drawPixmap(0, 0, self.scaledTroopCountMap) else: painter.fillRect(rect, QColor(0, 0, 0, 200)) painter.drawText(rect, Qt.AlignCenter, "Waiting for the game to start.") #remaining troops if self.game.yourTurn() and self.game.remainingTroops: troopText = "Remaining troops: %d" % self.game.remainingTroops troopRect = QRect(0, 0, painter.fontMetrics().width(troopText) + 8, painter.fontMetrics().height() + 8) troopRect.moveBottomLeft(rect.bottomLeft()) painter.setPen(Qt.white) painter.setBrush(QColor(0, 0, 0, 200)) painter.drawRect(troopRect) painter.drawText(troopRect, Qt.AlignCenter, troopText) painter.end()
def paintVerticalCell(self, painter: QPainter, hv: QHeaderView, cellIndex: QModelIndex, leafIndex: QModelIndex, logicalLeafIndex: int, styleOptions: QStyleOptionHeader, sectionRect: QRect, left: int): uniopt = QStyleOptionHeader(styleOptions) self.setForegroundBrush(uniopt, cellIndex) self.setBackgroundBrush(uniopt, cellIndex) width = self.cellSize(cellIndex, hv, uniopt).width() if cellIndex == leafIndex: width = sectionRect.width() - left top = self.currentCellLeft(cellIndex, leafIndex, logicalLeafIndex, sectionRect.top(), hv) height = self.currentCellWidth(cellIndex, leafIndex, logicalLeafIndex, hv) r = QRect(left, top, width, height) uniopt.text = cellIndex.data(Qt.DisplayRole) painter.save() uniopt.rect = r if cellIndex.data(Qt.UserRole): hv.style().drawControl(QStyle.CE_HeaderSection, uniopt, painter, hv) m = QMatrix() m.rotate(-90) painter.setWorldMatrix(m, True) new_r = QRect(0, 0, r.height(), r.width()) new_r.moveCenter(QPoint(-r.center().y(), r.center().x())) uniopt.rect = new_r hv.style().drawControl(QStyle.CE_HeaderLabel, uniopt, painter, hv) else: hv.style().drawControl(QStyle.CE_Header, uniopt, painter, hv) painter.restore() return left + width
def paintEvent(self, event=None): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) xOffset = self.width() / 3 yOffset = self.height() / 3 for x in range(3): for y in range(3): cell = self.grid[x][y] rect = (QRectF(x * xOffset, y * yOffset, xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5)) color = None if cell == RED: color = Qt.red elif cell == YELLOW: color = Qt.yellow if color is not None: painter.save() painter.setPen(Qt.black) painter.setBrush(color) painter.drawEllipse(rect.adjusted(2, 2, -2, -2)) painter.restore() if [x, y] == self.selected: painter.setPen(QPen(Qt.blue, 3)) else: painter.setPen(Qt.black) painter.drawRect(rect)
def paintEvent(self, event): if not self.displayedWhenStopped and not self.isAnimated(): return width = min(self.width(), self.height()) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) outerRadius = (width-1) * 0.5 innerRadius = (width-1) * 0.5 * 0.38 capsuleHeight = outerRadius - innerRadius capsuleWidth = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35 capsuleRadius = capsuleWidth / 2 for i in range(12): color = QColor(self.color) color.setAlphaF(float(1.0 - float(i / 12.0))) p.setPen(Qt.NoPen) p.setBrush(color) p.save() p.translate(self.rect().center()) p.rotate(self.angle - float(i * 30.0)) p.drawRoundedRect(-capsuleWidth * 0.5,\ -(innerRadius + capsuleHeight),\ capsuleWidth,\ capsuleHeight,\ capsuleRadius,\ capsuleRadius) p.restore()
def paintEvent(self, paint_event): """Paints the box""" painter = QPainter(self) rect = self.contentsRect() tile_count = 3 tile_size = rect.width() / tile_count painter.save() painter.translate(rect.x(), rect.y()) color_index = 0 for y in range(tile_count): if y % 2 == 1: color_index = 1 else: color_index = 0 for x in range(tile_count): tile_rect = QRect(x * tile_size, y * tile_size, tile_size, tile_size) painter.fillRect(tile_rect, self.tile_colors[color_index]) color_index += 1 if color_index >= len(self.tile_colors): color_index = 0 painter.restore() painter.fillRect(rect, self.color) QFrame.paintEvent(self, paint_event)
def paintEvent( self, event ): """ Das automatisch ausgelöste paintEvent, das das Widget bei jeder Fensterveränderung neu zeichnet. """ if self.__maximum > 0: frameWidth = 1 separatorWidth = 1 # Damit der Rahmen nicht irgendwie abgeschnitten wird, muß das Quadrat entsprechend kleiner sein. squareSideLength = 10 framePen = QPen( frameWidth ) framePen.setColor( self.__colorFrame ) squareSideLengthPlus = squareSideLength + 2 * frameWidth painter = QPainter( self ) windowWidth = self.width() / min( self.__maximum, self.__columnMax ) windowHeight = self.__maximum / self.__columnMax windowHeight = math.ceil( windowHeight ) windowHeight = self.height() / windowHeight side = min( windowWidth, windowHeight ) painter.setRenderHint( QPainter.Antialiasing ) # Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern. if ( not self.isEnabled() ): painter.setOpacity( .5 ) #painter.translate( float( windowWidth ), float( windowHeight ) ) painter.scale( side / squareSideLengthPlus, side / squareSideLengthPlus ) painter.setPen( framePen ) painter.setBrush( self.__colorEmpty ) painter.save() squareColumnIter = 0 squareLineIter = 0 squareCount = 0 for squareCount in range(self.__maximum): square = QRect( ( squareSideLength + separatorWidth ) * squareColumnIter + frameWidth * ( squareColumnIter + 1 ), ( squareSideLength + separatorWidth ) * squareLineIter + frameWidth * ( squareLineIter + 1 ), squareSideLength, squareSideLength ) painter.drawRect( square ) # Wir zeichnen die ausgekreuzten Quadrate if (self.__value > (self.__columnMax * squareLineIter + squareColumnIter)): painter.drawLine(square.bottomLeft(), square.topRight()) painter.drawLine(square.topLeft(), square.bottomRight()) squareColumnIter += 1 if ( squareColumnIter >= self.__columnMax ): squareColumnIter = 0 squareLineIter += 1 painter.restore()
def paintEvent(self,event): titleHeight = 40 bottomHeight = 50 #画标题背景 painter = QPainter(self) painter.save() linearGradient = QLinearGradient(0, 0,0,titleHeight) linearGradient.setColorAt(0, QColor(60,150,255)) linearGradient.setColorAt(0.1, QColor(6,88,200)) linearGradient.setColorAt(1, QColor(80,150,255)) painter.setBrush(QBrush(linearGradient)) contenRect = QRect(0, 0, self.width(), titleHeight) painter.fillRect(contenRect, QBrush(linearGradient)) painter.restore() #画标题内容 painter.save() painter.setPen(QPen(QColor(255, 255, 255),1)) font = painter.font() font.setPointSize(12) painter.setFont(font) painter.drawText(QPoint(10,25), self.title) painter.restore() #画中间白色背景 painter.save() painter.setPen(QPen(QColor(255, 255, 255),1)) brush = QBrush(QColor(242,242,242)) painter.setBrush(brush) contenRect = QRect(0, titleHeight, self.width()-1, self.height() - titleHeight - bottomHeight) # painter.fillRect(contenRect, brush) painter.drawRect(contenRect) painter.restore() #画提示信息内容 painter.save() painter.setPen(QPen(QColor(1, 1, 1),1)) font = painter.font() font.setPointSize(15) painter.setFont(font) fm = QFontMetrics(font) infoWidth = fm.width(self.hintInfo) painter.drawText(QPoint((self.width() - infoWidth - 10)/2, 150), self.hintInfo) painter.restore() #画底层背景 painter.save() brush = QBrush(QColor(219,234,255)) painter.setBrush(brush) contenRect = QRect(0, self.height() - bottomHeight, self.width(), bottomHeight) painter.fillRect(contenRect, brush) painter.restore()
def slot_canvasPrint(self): self.scene.clearSelection() self.fExportPrinter = QPrinter() dialog = QPrintDialog(self.fExportPrinter, self) if dialog.exec_(): painter = QPainter(self.fExportPrinter) painter.save() painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.TextAntialiasing) self.scene.render(painter) painter.restore()
def slot_canvasPrint(self): self.scene.clearSelection() self.fExportPrinter = QPrinter() dialog = QPrintDialog(self.fExportPrinter, self) if dialog.exec_(): painter = QPainter(self.fExportPrinter) painter.save() painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) self.scene.render(painter) painter.restore()
def paintEvent(self,event): painter = QPainter(self) painter.save() linearGradient = QLinearGradient(0,0,0,self.geometry().width()) linearGradient.setColorAt(0, QColor(60,150,255)) linearGradient.setColorAt(0.1, QColor(6,88,200)) linearGradient.setColorAt(1, QColor(80,150,255)) painter.setBrush(QBrush(linearGradient)) contenRect = QRect(0, 0, self.width(), self.topLine-10) painter.fillRect(contenRect, QBrush(linearGradient)) painter.restore() painterBack = QPainter(self) backBrush = QBrush(QColor(200,200,250)) painterBack.setBrush(backBrush) backRect = QRect(0,self.topLine-10,self.width(),self.height()) painterBack.fillRect(backRect, backBrush)
def paintEvent(self, event): painter = QPainter(self) event.accept() if not self.isEnabled(): painter.save() painter.setOpacity(0.2) painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect) painter.restore() elif self.isChecked() or self.isDown(): painter.drawPixmap(self.fPixmapRect, self.fPixmapDown, self.fPixmapRect) elif self.fIsHovered: painter.drawPixmap(self.fPixmapRect, self.fPixmapHover, self.fPixmapRect) else: painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect)
def genWINDPIXMAPS(): """prepare wind tiles""" tileset = Tileset(Preferences.windTilesetName) for wind in WINDS: for prevailing in False, True: pwind = PlayerWind(wind, tileset, prevailing) pMap = QPixmap(40, 40) pMap.fill(Qt.transparent) painter = QPainter(pMap) painter.setRenderHint(QPainter.Antialiasing) painter.scale(0.40, 0.40) pwind.paint(painter, QStyleOptionGraphicsItem()) for child in pwind.childItems(): if isinstance(child, QGraphicsSvgItem): painter.save() painter.translate(child.mapToParent(0.0, 0.0)) child.paint(painter, QStyleOptionGraphicsItem()) painter.restore() WINDPIXMAPS[(wind, prevailing)] = pMap
def paintEvent(self, paint_event): """Paints the box""" painter = QPainter(self) rect = self.contentsRect() tile_count = 3 tile_size = rect.width() / tile_count painter.save() painter.translate(rect.x(), rect.y()) for y in range(tile_count): for x in range(tile_count): color_index = (y * tile_count + x) % 2 tile_rect = QRect(x * tile_size, y * tile_size, tile_size, tile_size) painter.fillRect(tile_rect, self._tile_colors[color_index]) painter.restore() painter.fillRect(rect, self._color) QFrame.paintEvent(self, paint_event)
def genWINDPIXMAPS(): """prepare wind tiles""" tileset = Tileset(common.PREF.windTilesetName) for wind in WINDS: for prevailing in False, True: pwind = PlayerWind(wind, tileset, prevailing) pMap = QPixmap(40, 40) pMap.fill(Qt.transparent) painter = QPainter(pMap) painter.setRenderHint(QPainter.Antialiasing) painter.scale(0.40, 0.40) pwind.paint(painter, QStyleOptionGraphicsItem()) for child in pwind.childItems(): if isinstance(child, QGraphicsSvgItem): painter.save() painter.translate(child.mapToParent(0.0, 0.0)) child.paint(painter, QStyleOptionGraphicsItem()) painter.restore() WINDPIXMAPS[(wind, prevailing)] = pMap
def paintEvent(self, e): data = self.itemData(self.currentIndex(), Qt.UserRole) if data.isValid() and data.toPyObject() is not None: data = data.toPyObject() p = QStylePainter(self) p.setPen(self.palette().color(QPalette.Text)) opt = QStyleOptionComboBox() self.initStyleOption(opt) p.drawComplexControl(QStyle.CC_ComboBox, opt) painter = QPainter(self) painter.save() rect = p.style().subElementRect(QStyle.SE_ComboBoxFocusRect, opt, self) rect.adjust(+5, 0, -5, 0) pen = data painter.setPen(pen) middle = (rect.bottom() + rect.top()) / 2 painter.drawLine(rect.left(), middle, rect.right(), middle) painter.restore() else: QComboBox.paintEvent(self, e)
def paintEvent(self, ev): painter = QPainter(self) # calc bar offset y_offset = (self.height() - self._barHeight()) // 2 ## prevent negative offset y_offset = 0 if y_offset < 0 else y_offset # frame around fraction indicator painter.setBrush(self.palette().dark()) painter.save() ## no fill color b = painter.brush() b.setStyle(Qt.NoBrush) painter.setBrush(b) painter.drawRect(QRect(QPoint(0, y_offset), QSize(self._barWidth(), self._barHeight()))) painter.restore() # fraction indicator painter.drawRect(QRect(QPoint(0, y_offset), QSize(self._barWidth() * self._fraction, self._barHeight())))
def printViaQPainter(self): from os.path import isfile if isfile(self.filename): lines = open(self.filename) else: return a = self.filename.split('.') s = a[-1] fname = '' for i in range(len(a)-1) : fname += a[i] fname += '.pdf' self.printer.setOutputFileName(fname) self.printer.setOutputFormat(QPrinter.PdfFormat) if self.cmbOrientation.currentText() == 'landscape': self.printer.setOrientation(QPrinter.Landscape) pageRect = self.printer.pageRect() LeftMargin = 15 biggest = findBiggestLine(self.filename) bestSize = findBestFontSize(biggest,pageRect) sansFont = QFont("Courier", bestSize) sansLineHeight = QFontMetrics(sansFont).height() painter = QPainter(self.printer) page = 1 y = 20 cpage = codePage(self.cmbCodePage.currentText()) for line in lines: painter.save() painter.setFont(sansFont) y += sansLineHeight x = LeftMargin try: painter.drawText(x,y,line[:-1].decode(cpage)) except: painter.drawText(x,y,'CodePage error !!!') if y > (pageRect.height() - 54) : self.printer.newPage() y = 20 painter.restore() lines.close() self.accept()
def paintEvent( self, ev ): painter = QPainter(self) # calc bar offset y_offset =(self.height() - self._barHeight()) // 2 ## prevent negative offset y_offset = 0 if y_offset < 0 else y_offset # frame around fraction indicator painter.setBrush(self.palette().dark()) painter.save() ## no fill color b = painter.brush(); b.setStyle(Qt.NoBrush); painter.setBrush(b) painter.drawRect( QRect(QPoint(0, y_offset), QSize(self._barWidth(), self._barHeight()))) painter.restore() # fraction indicator painter.drawRect( QRect(QPoint(0, y_offset), QSize(self._barWidth()*self._fraction, self._barHeight())))
def paintEvent( self, event ): # Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern. frameWidth = 16 dotCenter = QPoint( 0, 0 ) color = self.__colorEmpty if self.__value: color = self.__colorFull # Damit der Rahmen nicht irgendwie abgeschnitten wird, muß der Kreis entsprechend kleiner sein. dotRadius = 100 framePen = QPen( frameWidth ) framePen.setColor( self.__colorFrame ) dotDiameter = 2 * dotRadius + frameWidth painter = QPainter( self ) windowWidth = self.width() windowHeight = float( self.height() ) side = min( windowWidth, windowHeight ) painter.setRenderHint( QPainter.Antialiasing ) if ( not self.isEnabled() ): painter.setOpacity( .5 ) painter.translate( side / 2, self.height() / 2 ) painter.scale( side / dotDiameter, side / dotDiameter ) painter.setPen( framePen ) painter.setBrush( color ) painter.save() painter.drawEllipse( dotCenter, dotRadius, dotRadius ) painter.restore()
def paintEvent(self, event=None): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) xOffset = self.width() / 3 yOffset = self.height() / 3 for x in range(3): for y in range(3): cell = self.grid[x][y] rect = (QRectF(x * xOffset, y * yOffset, xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5)) great_rect = QRectF(x * xOffset, y * yOffset, xOffset, yOffset) textToDraw = None if cell == X: textToDraw = "X" elif cell == O: textToDraw = "O" if textToDraw is not None: painter.save() painter.setPen(Qt.black) #painter.setBrush(color) #painter.drawEllipse(rect.adjusted(2, 2, -2, -2)) font = QFont() font.setPointSize(20) painter.setFont(font) painter.drawText(rect, Qt.AlignCenter, textToDraw) painter.restore() if [x, y] == self.selected: painter.setPen(QPen(Qt.blue, 3)) else: painter.setPen(Qt.black) painter.drawRect(rect) result = self.checkForGameEnd() if result: self.update() self.endGame(result) self.update()
def slot_canvasSaveImage(self): newPath = QFileDialog.getSaveFileName(self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)")) if newPath: self.scene.clearSelection() # FIXME - must be a better way... if newPath.endswith((".jpg", ".jpG", ".jPG", ".JPG", ".JPg", ".Jpg")): imgFormat = "JPG" elif newPath.endswith((".png", ".pnG", ".pNG", ".PNG", ".PNg", ".Png")): imgFormat = "PNG" else: # File-dialog may not auto-add the extension imgFormat = "PNG" newPath += ".png" self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32) painter = QPainter(self.fExportImage) painter.save() painter.setRenderHint(QPainter.Antialiasing) # TODO - set true, cleanup this painter.setRenderHint(QPainter.TextAntialiasing) self.scene.render(painter) self.fExportImage.save(newPath, imgFormat, 100) painter.restore()
def paintEvent(self, event): if self._isRunning: anglestep = 360. / self._steps fillsteps = self._fillsteps factor = min(self.width(), self.height()) / 16. bw = self._bw p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) p.scale(factor, factor) p.setPen(Qt.NoPen) for i in range(self._steps): x1, y1 = self._coords[i] c = fillsteps[self._steps - 1 - i] a = anglestep * i p.setBrush(QBrush(QColor.fromRgbF(bw, bw, bw, c))) p.save() p.translate(x1 - 2, y1 - 1) p.translate(2, 1) p.rotate(a) p.translate(-2, -1) p.drawPath(self._path) p.restore()
def paintEvent(self, e): time = QTime.currentTime() qp = QPainter() qp.begin(self) #qp.setRenderHint(QPainter.Antialiasing) # 开启这个抗锯齿,会很占cpu的! qp.translate(self.width() / 2, self.height() / 2) qp.scale(self.side / 200.0, self.side / 200.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.hourColor) qp.save() qp.rotate(30.0 * ((time.hour() + time.minute()/ 60.0))) qp.drawConvexPolygon(self.hourHand) qp.restore() qp.setPen(self.hourColor) for i in range(12): qp.drawLine(88, 0, 96, 0) qp.rotate(30.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.minuteColor) qp.save() qp.rotate(6.0 * ((time.minute() + (time.second()+time.msec()/1000.0) / 60.0))) qp.drawConvexPolygon(self.minuteHand) qp.restore() qp.setPen(self.minuteColor) for i in range(60): if (i % 5) is not 0: qp.drawLine(92, 0, 96, 0) qp.rotate(6.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.secondColor) qp.save() qp.rotate(6.0*(time.second()+time.msec()/1000.0)) qp.drawConvexPolygon(self.secondHand) qp.restore() qp.end()
def paintEvent(self, e): time = QTime.currentTime() qp = QPainter() qp.begin(self) #qp.setRenderHint(QPainter.Antialiasing) # 开启这个抗锯齿,会很占cpu的! qp.translate(self.width() / 2, self.height() / 2) qp.scale(self.side / 200.0, self.side / 200.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.hourColor) qp.save() qp.rotate(30.0 * ((time.hour() + time.minute() / 60.0))) qp.drawConvexPolygon(self.hourHand) qp.restore() qp.setPen(self.hourColor) for i in range(12): qp.drawLine(88, 0, 96, 0) qp.rotate(30.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.minuteColor) qp.save() qp.rotate(6.0 * ((time.minute() + (time.second() + time.msec() / 1000.0) / 60.0))) qp.drawConvexPolygon(self.minuteHand) qp.restore() qp.setPen(self.minuteColor) for i in range(60): if (i % 5) is not 0: qp.drawLine(92, 0, 96, 0) qp.rotate(6.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.secondColor) qp.save() qp.rotate(6.0 * (time.second() + time.msec() / 1000.0)) qp.drawConvexPolygon(self.secondHand) qp.restore() qp.end()
def paintEvent(self, event): painter = QPainter(self) width = self.width() height = self.height() if self.scales_visible: curve_width = width - self.y_scale.total_width - self.curve_to_scale - self.curve_outer_border curve_height = height - self.y_scale_height_offset - self.x_scale.total_height - self.curve_to_scale else: curve_width = width - self.curve_outer_border - self.curve_outer_border curve_height = height - self.curve_outer_border - self.curve_outer_border if DEBUG: painter.fillRect(0, 0, width, height, Qt.green) # fill canvas if self.scales_visible: canvas_x = self.y_scale.total_width + self.curve_to_scale - self.curve_outer_border canvas_y = self.y_scale_height_offset - self.curve_outer_border else: canvas_x = 0 canvas_y = 0 canvas_width = self.curve_outer_border + curve_width + self.curve_outer_border canvas_height = self.curve_outer_border + curve_height + self.curve_outer_border painter.fillRect(canvas_x, canvas_y, canvas_width, canvas_height, self.canvas_color) # draw cross hair at cursor position if self.cross_hair_visible: p = self.mapFromGlobal(QCursor.pos()) p_x = p.x() p_y = p.y() if p_x >= canvas_x and p_x < canvas_x + canvas_width and \ p_y >= canvas_y and p_y < canvas_y + canvas_height: painter.setPen(QPen(QColor(190, 190, 190), 1, Qt.DashLine)) painter.drawLine(canvas_x, p_y, canvas_x + canvas_width - 1, p_y) painter.drawLine(p_x, canvas_y, p_x, canvas_y + canvas_height - 1) # draw canvas border if self.curve_outer_border > 0: painter.setPen(QColor(190, 190, 190)) painter.drawRect( canvas_x, canvas_y, canvas_width - 1, canvas_height - 1) # -1 to accommodate the 1px width of the border painter.setPen(Qt.black) if DEBUG: painter.fillRect(canvas_x + self.curve_outer_border, canvas_y + self.curve_outer_border, curve_width, curve_height, Qt.cyan) # draw scales y_min_scale = self.y_scale.value_min y_max_scale = self.y_scale.value_max factor_x = float(curve_width) / self.history_length_x factor_y = float(curve_height - 1) / max( y_max_scale - y_min_scale, EPSILON) # -1 to accommodate the 1px width of the curve if self.scales_visible: self.draw_x_scale(painter, factor_x) self.draw_y_scale(painter, curve_height, factor_y) # draw curves if self.x_min != None and self.x_max != None: x_min = self.x_min x_max = self.x_max if self.scales_visible: curve_x_offset = 0 else: curve_x_offset = round( (self.history_length_x - (x_max - x_min)) * factor_x) painter.save() painter.translate( canvas_x + self.curve_outer_border + curve_x_offset, canvas_y + self.curve_outer_border + curve_height - 1 + self.curve_y_offset ) # -1 to accommodate the 1px width of the curve painter.scale(factor_x, -factor_y) painter.translate(-x_min, -y_min_scale) for c in range(len(self.curves_x)): if not self.curves_visible[c]: continue curve_x = self.curves_x[c] curve_y = self.curves_y[c] path = QPainterPath() lineTo = path.lineTo path.moveTo(curve_x[0], curve_y[0]) for i in xrange(1, len(curve_x)): lineTo(curve_x[i], curve_y[i]) painter.setPen(self.plots[c][1]) painter.drawPath(path) painter.restore()
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1,-1) self._painter.translate(0,-canvas.height()) Renderer.set_canvas(self,canvas) def _get_canvas_size(self,pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs,ys = zip( transform.map(0.0,0.0), transform.map(0.0,float(self.size[1])), transform.map(float(self.size[0]),float(self.size[1])), transform.map(float(self.size[0]),0.0) ) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin//self._grid_spacing), int(xmax//self._grid_spacing + 1)) y_ticks = (int(ymin//self._grid_spacing), int(ymax//self._grid_spacing + 1)) self._painter.drawLines( [QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks)]) self._painter.drawLines( [QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks)]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor,factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx,dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0,0,self.size[0],self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self,color=0, thickness=0): """Sets the line color and thickness. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(QPen(self.__qcolor(color),thickness)) def set_brush(self,color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self,points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb = None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx-ra,cy-ra,2*ra,2*rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x,y,w,h)) def draw_text(self, text, x, y, bgcolor = 0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1,y1,x2,y2))
def paintVerticalCell(self, painter: QPainter, hv: QHeaderView, cellIndex: QModelIndex, leafIndex: QModelIndex, logicalLeafIndex: int, styleOptions: QStyleOptionHeader, sectionRect: QRect, left: int): uniopt = QStyleOptionHeader(styleOptions) self.setForegroundBrush(uniopt, cellIndex) self.setBackgroundBrush(uniopt, cellIndex) width=self.cellSize(cellIndex, hv, uniopt).width() if cellIndex==leafIndex: width=sectionRect.width()-left top=self.currentCellLeft(cellIndex, leafIndex, logicalLeafIndex, sectionRect.top(), hv) height=self.currentCellWidth(cellIndex, leafIndex, logicalLeafIndex, hv) r = QRect(left, top, width, height) uniopt.text = cellIndex.data(Qt.DisplayRole) painter.save() uniopt.rect = r if cellIndex.data(Qt.UserRole): hv.style().drawControl(QStyle.CE_HeaderSection, uniopt, painter, hv) m = QMatrix() m.rotate(-90) painter.setWorldMatrix(m, True) new_r = QRect(0, 0, r.height(), r.width()) new_r.moveCenter(QPoint(-r.center().y(), r.center().x())) uniopt.rect = new_r hv.style().drawControl(QStyle.CE_HeaderLabel, uniopt, painter, hv) else: hv.style().drawControl(QStyle.CE_Header, uniopt, painter, hv) painter.restore() return left+width def paintVerticalSection(self, painter: QPainter, sectionRect: QRect, logicalLeafIndex: int, hv: QHeaderView, styleOptions: QStyleOptionHeader, leafIndex: QModelIndex): oldBO = painter.brushOrigin() left = sectionRect.x() indexes = QModelIndexList(self.parentIndexes(leafIndex)) for i in range(indexes.size()): realStyleOptions = QStyleOptionHeader(styleOptions) if i<indexes.size()-1 and (realStyleOptions.state&QStyle.State_Sunken or realStyleOptions.state&QStyle.State_On): t = QStyle.State(QStyle.State_Sunken | QStyle.State_On) realStyleOptions.state = realStyleOptions.state&~t #FIXME: parent items are not highlighted left=self.paintVerticalCell(painter, hv, indexes[i], leafIndex, logicalLeafIndex, realStyleOptions, sectionRect, left) painter.setBrushOrigin(oldBO) def __init__(self, orientation: Qt.Orientation, parent: QWidget): super().__init__(orientation, parent) self._pd = self.private_data() self.sectionResized.connect(self.on_sectionResized) self.setHighlightSections(self.options.get("highlightSections")) self.setClickable(self.options.get("clickable")) self.show() #force to be visible getattr(parent, "set%sHeader"%("Horizontal", "Vertical")[orientation!=Qt.Horizontal])(self) self.sectionMoved.connect(self.on_sectionMoved) def on_sectionMoved(self, logicalIndex, oldVisualIndex, newVisualIndex): view, model = self.parent(), self.parent().model() if not hasattr(model, "reorder"): return #reorder underlying data of models with /reorder/ def only if getattr(self, "manual_move", False): self.manual_move=False return self.manual_move=True self.moveSection(newVisualIndex, oldVisualIndex) #cancel move if model.reorder(oldVisualIndex, newVisualIndex, self.orientation()): #Reorder column widths / row heights horizontal = self.orientation()==Qt.Horizontal itemSize = (view.rowHeight, view.columnWidth)[horizontal] setItemSize = (view.setRowHeight, view.setColumnWidth)[horizontal] rng = sorted((oldVisualIndex, newVisualIndex)) options = [(itemSize(i), i) for i in range(rng[0], rng[1]+1)] options.insert(newVisualIndex-rng[0], options.pop(oldVisualIndex-rng[0])) for i, col in enumerate(range(rng[0], rng[1]+1)): setItemSize(col, options[i][0]) getattr(view, "select"+("Row", "Column")[horizontal])(newVisualIndex) #FIXME: don't select if sorting is enable? if self.isSortIndicatorShown(): sortIndIndex = next((i for i, o in enumerate(options) if o[1]==self.sortIndicatorSection()), None) if sortIndIndex is not None: #sort indicator is among sections being reordered self.setSortIndicator(sortIndIndex+rng[0], self.sortIndicatorOrder()) #FIXME: does unnecessary sorting model.layoutChanged.emit() #update view def styleOptionForCell(self, logicalInd: int)->QStyleOptionHeader: opt = QStyleOptionHeader() self.initStyleOption(opt) if self.isSortIndicatorShown() and self.sortIndicatorSection()==logicalInd: opt.sortIndicator = (QStyleOptionHeader.SortUp, QStyleOptionHeader.SortDown)[self.sortIndicatorOrder()==Qt.AscendingOrder] if self.window().isActiveWindow(): opt.state = opt.state|QStyle.State_Active opt.textAlignment = Qt.AlignCenter opt.iconAlignment = Qt.AlignVCenter opt.section = logicalInd visual = self.visualIndex(logicalInd) if self.count() == 1: opt.position = QStyleOptionHeader.OnlyOneSection else: if visual == 0: opt.position = QStyleOptionHeader.Beginning else: opt.position = QStyleOptionHeader.End if visual==self.count()-1 else QStyleOptionHeader.Middle if self.isClickable(): # if logicalIndex == d.hover: # ... if self.highlightSections() and self.selectionModel(): if self.orientation()==Qt.Horizontal: if self.selectionModel().columnIntersectsSelection(logicalInd, self.rootIndex()): opt.state = opt.state|QStyle.State_On if self.selectionModel().isColumnSelected(logicalInd, self.rootIndex()): opt.state = opt.state|QStyle.State_Sunken else: if self.selectionModel().rowIntersectsSelection(logicalInd, self.rootIndex()): opt.state = opt.state|QStyle.State_On if self.selectionModel().isRowSelected(logicalInd, self.rootIndex()): opt.state = opt.state|QStyle.State_Sunken if self.selectionModel(): previousSelected=False if self.orientation()==Qt.Horizontal: previousSelected = self.selectionModel().isColumnSelected(self.logicalIndex(visual - 1), self.rootIndex()) else: previousSelected = self.selectionModel().isRowSelected(self.logicalIndex(visual - 1), self.rootIndex()) nextSelected=False if self.orientation()==Qt.Horizontal: nextSelected = self.selectionModel().isColumnSelected(self.logicalIndex(visual + 1), self.rootIndex()) else: nextSelected = self.selectionModel().isRowSelected(self.logicalIndex(visual + 1), self.rootIndex()) if previousSelected and nextSelected: opt.selectedPosition = QStyleOptionHeader.NextAndPreviousAreSelected else: if previousSelected: opt.selectedPosition = QStyleOptionHeader.PreviousIsSelected else: if nextSelected: opt.selectedPosition = QStyleOptionHeader.NextIsSelected else: opt.selectedPosition = QStyleOptionHeader.NotAdjacent return opt def sectionSizeFromContents(self, logicalIndex: int)->QSize: if self._pd.headerModel: curLeafIndex = QModelIndex(self._pd.leafIndex(logicalIndex)) if curLeafIndex.isValid(): styleOption = QStyleOptionHeader(self.styleOptionForCell(logicalIndex)) s = QSize(self._pd.cellSize(curLeafIndex, self, styleOption)) curLeafIndex=curLeafIndex.parent() while curLeafIndex.isValid(): if self.orientation() == Qt.Horizontal: s.setHeight(s.height()+self._pd.cellSize(curLeafIndex, self, styleOption).height()) else: s.setWidth(s.width()+self._pd.cellSize(curLeafIndex, self, styleOption).width()) curLeafIndex=curLeafIndex.parent() return s return super().sectionSizeFromContents(logicalIndex) def paintSection(self, painter: QPainter, rect: QRect, logicalIndex: int): if rect.isValid(): leafIndex = QModelIndex(self._pd.leafIndex(logicalIndex)) if leafIndex.isValid(): if self.orientation() == Qt.Horizontal: self._pd.paintHorizontalSection(painter, rect, logicalIndex, self, self.styleOptionForCell(logicalIndex), leafIndex) else: self._pd.paintVerticalSection(painter, rect, logicalIndex, self, self.styleOptionForCell(logicalIndex), leafIndex) return super().paintSection(painter, rect, logicalIndex) def on_sectionResized(self, logicalIndex: int): if self.isSectionHidden(logicalIndex): return leafIndex = QModelIndex(self._pd.leafIndex(logicalIndex)) if leafIndex.isValid(): leafsList = QModelIndexList(self._pd.leafs(self._pd.findRootIndex(leafIndex))) for n in range(leafsList.indexOf(leafIndex), 0, -1): logicalIndex-=1 w = self.viewport().width() h = self.viewport().height() pos = self.sectionViewportPosition(logicalIndex) r = QRect(pos, 0, w - pos, h) if self.orientation() == Qt.Horizontal: if self.isRightToLeft(): r.setRect(0, 0, pos + self.sectionSize(logicalIndex), h) else: r.setRect(0, pos, w, h - pos) self.viewport().update(r.normalized()) def setModel(self, model): super().setModel(model) model.layoutChanged.connect(self.layoutChanged) self.layoutChanged() def layoutChanged(self): if self.model(): self._pd.initFromNewModel(self.orientation(), self.model()) axis = ("column", "row")[self.orientation()!=Qt.Horizontal] cnt = getattr(self.model(), axis+"Count")(QModelIndex()) if cnt: self.initializeSections(0, cnt-1) MultiIndexHeaderView=HierarchicalHeaderView class DataFrameModel(QtCore.QAbstractTableModel): #na_values:least|greatest - for sorting options = {"striped": True, "stripesColor": "#fafafa", "na_values": "least", "tooltip_min_len": 21} def __init__(self, dataframe=None): super().__init__() self.setDataFrame(dataframe if dataframe is not None else pd.DataFrame()) def setDataFrame(self, dataframe): self.df = dataframe.copy() # self.df_full = self.df self.layoutChanged.emit() def rowCount(self, parent): return len(self.df) def columnCount(self, parent): return len(self.df.columns) def readLevel(self, y=0, xs=0, xe=None, orient=None): c = getattr(self.df, ("columns", "index")[orient!=HorizontalHeaderDataRole]) if not hasattr(c, "levels"): #not MultiIndex return [QtGui.QStandardItem(str(i)) for i in c] sibl = [] section_start, v, xe = xs, None, xe or len(c) for i in range(xs, xe): label = c.labels[y][i] if label!=v: if y+1<len(c.levels) and i>xs: children = self.readLevel(y+1, section_start, i, orient=orient) sibl[-1].appendRow(children) item = QtGui.QStandardItem(str(c.levels[y][label])) sibl.append(item) section_start = i v=label if y+1<len(c.levels): children = self.readLevel(y+1, section_start, orient=orient) sibl[-1].appendRow(children) return sibl def data(self, index, role): row, col = index.row(), index.column() if role in (Qt.DisplayRole, Qt.ToolTipRole): ret = self.df.iat[row, col] if ret is not None and ret==ret: #convert to str except for None, NaN, NaT if isinstance(ret, float): ret = "{:n}".format(ret) elif isinstance(ret, datetime.date): #FIXME: show microseconds optionally ret = ret.strftime(("%x", "%c")[isinstance(ret, datetime.datetime)]) else: ret = str(ret) if role == Qt.ToolTipRole: if len(ret)<self.options["tooltip_min_len"]: ret = "" return ret elif role == Qt.BackgroundRole: if self.options["striped"] and row%2: return QBrush(QColor(self.options["stripesColor"])) elif role in (HorizontalHeaderDataRole, VerticalHeaderDataRole): hm = QtGui.QStandardItemModel() hm.appendRow(self.readLevel(orient=role)) return hm def reorder(self, oldIndex, newIndex, orientation): "Reorder columns / rows" horizontal = orientation==Qt.Horizontal cols = list(self.df.columns if horizontal else self.df.index) cols.insert(newIndex, cols.pop(oldIndex)) self.df = self.df[cols] if horizontal else self.df.T[cols].T return True # def filter(self, filt=None): # self.df = self.df_full if filt is None else self.df[filt] # self.layoutChanged.emit() def headerData(self, section, orientation, role): if role != Qt.DisplayRole: return label = getattr(self.df, ("columns", "index")[orientation!=Qt.Horizontal])[section] # return label if type(label) is tuple else label return ("\n", " | ")[orientation!=Qt.Horizontal].join(str(i) for i in label) if type(label) is tuple else str(label) def dataFrame(self): return self.df def sort(self, column, order): # print("sort", column, order) #FIXME: double sort after setSortingEnabled(True) if len(self.df): asc = order==Qt.AscendingOrder na_pos = 'first' if (self.options["na_values"]=="least")==asc else 'last' self.df.sort_values(self.df.columns[column], ascending=asc, inplace=True, na_position=na_pos) self.layoutChanged.emit() if __name__=="__main__": import sys, locale locale.setlocale(locale.LC_ALL, '') #system locale settings app = QtGui.QApplication(sys.argv) form = QtGui.QWidget() form.setAttribute(Qt.WA_DeleteOnClose) #http://stackoverflow.com/a/27178019/1119602 form.setMinimumSize(700, 260) view = QtGui.QTableView() QtGui.QVBoxLayout(form).addWidget(view) form.show() #Prepare data tuples=[('bar', 'one', 'q'), ('bar', 'two', 'q'), ('baz', 'one', 'q'), ('baz', 'two', 'q'), ('foo', 'one', 'q'), ('foo', 'two', 'q'), ('qux', 'one', 'q'), ('qux', 'two', 'q')] index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third']) df=pd.DataFrame(pd.np.random.randn(6, 6), index=index[:6], columns=index[:6]) print("DataFrame:\n%s"%df) #Prepare view # oldh, oldv = view.horizontalHeader(), view.verticalHeader() # oldh.setParent(form), oldv.setParent(form) #Save old headers for some reason MultiIndexHeaderView(Qt.Horizontal, view) MultiIndexHeaderView(Qt.Vertical, view) view.horizontalHeader().setMovable(True) #reorder DataFrame columns manually #Set data view.setModel(DataFrameModel(df)) view.resizeColumnsToContents() view.resizeRowsToContents() #Set sorting enabled (after setting model) view.setSortingEnabled(True) sys.exit(app.exec())
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1, -1) self._painter.translate(0, -canvas.height()) Renderer.set_canvas(self, canvas) def _get_canvas_size(self, pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs, ys = zip(transform.map(0.0, 0.0), transform.map(0.0, float(self.size[1])), transform.map(float(self.size[0]), float(self.size[1])), transform.map(float(self.size[0]), 0.0)) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin // self._grid_spacing), int(xmax // self._grid_spacing + 1)) y_ticks = (int(ymin // self._grid_spacing), int(ymax // self._grid_spacing + 1)) self._painter.drawLines([ QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks) ]) self._painter.drawLines([ QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks) ]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor, factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx, dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0, 0, self.size[0], self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self, color): """Sets the line color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(self.__qcolor(color)) def set_brush(self, color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self, points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon( QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb=None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx - ra, cy - ra, 2 * ra, 2 * rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x, y, w, h)) def draw_text(self, text, x, y, bgcolor=0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1, y1, x2, y2))
class Meter(QtGui.QWidget): """ a PyQt instance of QtMeter from Qt example code """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.value = 0 self.minValue = 0 self.maxValue = 100 self.logo = "" self.scaleMajor = 10 self.scaleMijor = 10 self.startAngle = 60 self.endAngle = 60 self.crownColor = Qt.blue self.foreground = Qt.green self.background = Qt.black self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(200) self.resize(200, 200) def updateValue(self): pass def paintEvent(self, QPaintEvent): self.updateValue() self.side = min(self.width(), self.height()) self.painter = QPainter() self.painter.begin(self) #self.painter.setRenderHint(QPainter.Antialiasing) self.painter.translate(self.width() / 2, self.height() / 2) self.painter.scale(self.side / 200.0, self.side / 200.0) self.painter.setPen(Qt.NoPen) self.drawCrown() self.drawBackgroud() self.drawLogo() self.drawScale() self.drawScaleNum() self.drawNumbericValue() self.drawPointer() self.painter.end() def setValue(self, updatefun): self.value = updatefun() def setLogo(self, logo): self.logo = logo def drawCrown(self): self.painter.save() self.painter.setPen(QtGui.QPen(self.crownColor, 3)) self.painter.drawEllipse(-92, -92, 184, 184) self.painter.restore() def drawBackgroud(self): self.painter.save() self.painter.setBrush(self.background) self.painter.drawEllipse(-92, -92, 184, 184) self.painter.restore() def drawScale(self): self.painter.save() self.painter.rotate(self.startAngle) self.painter.setPen(self.foreground) steps = self.scaleMajor * self.scaleMijor angleStep = (360.0 - self.startAngle - self.endAngle) / steps pen = QtGui.QPen(self.painter.pen()) for i in xrange(steps + 1): if i % self.scaleMajor == 0: pen.setWidth(1) self.painter.setPen(pen) self.painter.drawLine(0, 62, 0, 72) else: pen.setWidth(0) self.painter.setPen(pen) self.painter.drawLine(0, 62, 0, 65) self.painter.rotate(angleStep) self.painter.restore() def drawScaleNum(self): self.painter.save() self.painter.setPen(self.foreground) startRad = (360 - self.startAngle - 90) * (3.14 / 180) deltaRad = (360 - self.startAngle - self.endAngle) * (3.14 / 180) / self.scaleMajor fm = QtGui.QFontMetricsF(self.font()) for i in xrange(self.scaleMajor + 1): sina = sin(startRad - i * deltaRad) cosa = cos(startRad - i * deltaRad) tmpVal = 1.0 * i * ((self.maxValue - self.minValue) / self.scaleMajor) + self.minValue numstr = QString("%1").arg(tmpVal) w = fm.size(Qt.TextSingleLine, numstr).width() h = fm.size(Qt.TextSingleLine, numstr).height() x = 82 * cosa - w / 2 y = -82 * sina + h / 4 self.painter.drawText(x, y, numstr) self.painter.restore() def drawLogo(self): self.painter.save() self.painter.setPen(self.foreground) self.painter.setBrush(self.foreground) logostr = QString(self.logo) fm = QtGui.QFontMetricsF(self.font()) w = fm.size(Qt.TextSingleLine, logostr).width() self.painter.drawText(-w / 2, -30, logostr) self.painter.restore() def drawNumbericValue(self): self.painter.save() color = QtGui.QColor(150, 150, 200) pen = self.painter.pen() pen.setWidth(3) self.painter.setPen(pen) self.painter.setPen(color) self.painter.drawRect(-30, 30, 60, 14) cpustr = QString("%1").arg(self.value) fm = QtGui.QFontMetricsF(self.font()) w = fm.size(Qt.TextSingleLine, cpustr).width() self.painter.setPen(self.foreground) self.painter.drawText(-w / 2, 42, cpustr) self.painter.restore() def drawPointer(self): self.painter.save() self.pointerHand = QPolygon([-2, 0, 2, 0, 0, 60]) self.pointerColor = QColor(127, 0, 127) self.painter.setBrush(self.pointerColor) self.painter.rotate(self.startAngle) degRotate = (360.0 - self.startAngle - self.endAngle) / ( self.maxValue - self.minValue) * (self.value - self.minValue) self.painter.rotate(degRotate) self.painter.drawConvexPolygon(self.pointerHand) self.painter.restore()
def paintEvent(self, event): # Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern. frameWidth = 16 dotCenter = QPoint(0, 0) shiftCenter = dotCenter # Damit der Rahmen nicht irgendwie abgeschnitten wird, muß der Kreis entsprechend kleiner sein. dotRadius = 100 framePen = QPen() framePen.setWidth(frameWidth) framePen.setColor(self._colorFrame) dotDiameter = 2 * dotRadius + frameWidth painter = QPainter(self) windowWidth = self.width() // self.__maximum windowHeight = float(self.height()) side = min(windowWidth, windowHeight) painter.setRenderHint(QPainter.Antialiasing) if (not self.isEnabled()): painter.setOpacity(.5) painter.translate(side / 2, self.height() / 2) painter.scale(side / dotDiameter, side / dotDiameter) painter.setPen(framePen) painter.setBrush(self._colorFull) painter.save() for i in range(self.__value): shiftCenter = dotCenter + QPoint(0 + dotDiameter * i, 0) painter.drawEllipse(shiftCenter, dotRadius, dotRadius) ## if (v_forbiddenValues.contains(i+1)){ ## painter.drawEllipse(shiftCenter, dotRadius/2, dotRadius/2); painter.restore() painter.setBrush(self._colorEmpty) painter.save() for i in range(self.__value, self.__maximum): shiftCenter = dotCenter + QPoint(0 + dotDiameter * i, 0) painter.drawEllipse(shiftCenter, dotRadius, dotRadius) j = i + 1 if (j in self.__forbiddenValues): dotRadiusHalf = dotRadius / 2 painter.drawLine(shiftCenter.x() - dotRadiusHalf, shiftCenter.y() - dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() + dotRadiusHalf) painter.drawLine(shiftCenter.x() - dotRadiusHalf, shiftCenter.y() + dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() - dotRadiusHalf) ## for (int i = 0; i < v_forbiddenValues.count(); ++i) { ## shiftCenter = dotCenter + QPoint( 0 + dotDiameter * (v_forbiddenValues.at(i) - 1), 0 ); ## ## painter.drawLine(shiftCenter.x()-dotDiameter/2, shiftCenter.y()-dotDiameter/2, shiftCenter.x()+dotDiameter/2, shiftCenter.y()+dotDiameter/2); ## ## painter.drawLine(shiftCenter.x()+dotDiameter/2, shiftCenter.y()-dotDiameter/2, shiftCenter.x()-dotDiameter/2, shiftCenter.y()+dotDiameter/2); ## painter.drawEllipse(shiftCenter, dotRadius/2, dotRadius/2); ## } painter.restore()
def paintEvent(self, event): painter = QPainter(self) width = self.width() height = self.height() if DEBUG: painter.fillRect(0, 0, width, height, Qt.blue) else: painter.fillRect(event.rect(), self.plot.canvas_color) y_min_scale = self.plot.y_scale.value_min y_max_scale = self.plot.y_scale.value_max factor_x = float(width) / self.plot.x_diff factor_y = float(height - 1) / max( y_max_scale - y_min_scale, EPSILON) # -1 to accommodate the 1px width of the curve if self.plot.x_min != None and self.plot.x_max != None: x_min = self.plot.x_min x_max = self.plot.x_max if self.plot.curve_start == 'left': curve_x_offset = 0 else: curve_x_offset = round( (self.plot.x_diff - (x_max - x_min)) * factor_x) transform = QTransform() transform.translate( curve_x_offset, height - 1 + self.plot.curve_y_offset ) # -1 to accommodate the 1px width of the curve transform.scale(factor_x, -factor_y) transform.translate(-x_min, -y_min_scale) if self.plot.curve_motion_granularity > 1: self.plot.partial_update_width = math.ceil( transform.map(QLineF(0, 0, 1.5, 0)).length()) inverted_event_rect = transform.inverted()[0].mapRect( QRectF(event.rect())) painter.save() painter.setTransform(transform) if False and self.plot.curves_visible[0]: # Currently unused support for bar graphs. # If we need this later on we should add an option to the # PlotWidget for it. # I tested this for the Sound Pressure Level Bricklet and it works, # but it didnt't look good. curve_x = self.plot.curves_x[0] curve_y = self.plot.curves_y[0] t = time.time() if self.max_points == None: self.max_points = [] for y in curve_y: self.max_points.append((t, y)) else: for i in range(len(curve_y)): if (curve_y[i] > self.max_points[i][1]) or ( (t - self.max_points[i][0]) > 5): self.max_points[i] = (t, curve_y[i]) for i in range(len(self.plot.curves_x[0])): painter.setPen(self.plot.curve_configs[0].color) painter.drawLine(QPoint(curve_x[i], 0), QPoint(curve_x[i], curve_y[i])) painter.setPen(Qt.white) painter.drawLine(QPoint(curve_x[i], curve_y[i]), QPoint(curve_x[i], y_max_scale)) painter.setPen(Qt.darkGreen) painter.drawPoint(QPoint(curve_x[i], self.max_points[i][1])) else: for c in range(len(self.plot.curves_x)): if not self.plot.curves_visible[c]: continue curve_x = self.plot.curves_x[c] curve_y = self.plot.curves_y[c] path = QPainterPath() lineTo = path.lineTo if self.plot.curve_motion_granularity > 1: start = max( min( bisect.bisect_left(curve_x, inverted_event_rect.left()), len(curve_x) - 1) - 1, 0) else: start = 0 path.moveTo(curve_x[start], curve_y[start]) for i in xrange(start + 1, len(curve_x)): lineTo(curve_x[i], curve_y[i]) painter.setPen(self.plot.curve_configs[c].color) painter.drawPath(path) painter.restore()
class Meter(QtGui.QWidget): """ a PyQt instance of QtMeter from Qt example code """ def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.value = 0 self.minValue = 0 self.maxValue = 100 self.logo = "" self.scaleMajor = 10 self.scaleMijor = 10 self.startAngle = 60 self.endAngle = 60 self.crownColor = Qt.blue self.foreground = Qt.green self.background = Qt.black self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(200) self.resize(200,200) def updateValue(self): pass def paintEvent(self,QPaintEvent): self.updateValue() self.side = min(self.width(),self.height()) self.painter = QPainter() self.painter.begin(self) #self.painter.setRenderHint(QPainter.Antialiasing) self.painter.translate(self.width()/2,self.height()/2) self.painter.scale(self.side / 200.0, self.side / 200.0) self.painter.setPen(Qt.NoPen) self.drawCrown() self.drawBackgroud() self.drawLogo() self.drawScale() self.drawScaleNum() self.drawNumbericValue() self.drawPointer() self.painter.end() def setValue(self,updatefun): self.value = updatefun() def setLogo(self,logo): self.logo = logo def drawCrown(self): self.painter.save() self.painter.setPen(QtGui.QPen(self.crownColor, 3)) self.painter.drawEllipse(-92, -92, 184, 184) self.painter.restore() def drawBackgroud(self): self.painter.save() self.painter.setBrush(self.background) self.painter.drawEllipse(-92, -92, 184, 184) self.painter.restore() def drawScale(self): self.painter.save() self.painter.rotate(self.startAngle) self.painter.setPen(self.foreground) steps = self.scaleMajor * self.scaleMijor angleStep = (360.0 - self.startAngle - self.endAngle) /steps pen = QtGui.QPen(self.painter.pen()) for i in xrange(steps+1): if i % self.scaleMajor == 0: pen.setWidth(1) self.painter.setPen(pen) self.painter.drawLine(0, 62, 0, 72) else: pen.setWidth(0) self.painter.setPen(pen) self.painter.drawLine(0, 62, 0, 65) self.painter.rotate(angleStep) self.painter.restore() def drawScaleNum(self): self.painter.save() self.painter.setPen(self.foreground) startRad = (360 - self.startAngle - 90) * (3.14 / 180) deltaRad = (360 - self.startAngle - self.endAngle) * (3.14 / 180) / self.scaleMajor fm = QtGui.QFontMetricsF(self.font()) for i in xrange(self.scaleMajor+1): sina = sin(startRad - i * deltaRad) cosa = cos(startRad - i * deltaRad) tmpVal = 1.0 * i *((self.maxValue - self.minValue) / self.scaleMajor) + self.minValue numstr = QString( "%1" ).arg(tmpVal) w = fm.size(Qt.TextSingleLine,numstr).width() h = fm.size(Qt.TextSingleLine,numstr).height() x = 82 * cosa - w / 2 y = -82 * sina + h / 4 self.painter.drawText(x, y, numstr) self.painter.restore() def drawLogo(self): self.painter.save() self.painter.setPen(self.foreground) self.painter.setBrush(self.foreground) logostr = QString(self.logo) fm = QtGui.QFontMetricsF(self.font()) w = fm.size(Qt.TextSingleLine,logostr).width() self.painter.drawText(-w / 2, -30, logostr) self.painter.restore() def drawNumbericValue(self): self.painter.save() color = QtGui.QColor(150, 150, 200) pen = self.painter.pen() pen.setWidth(3) self.painter.setPen(pen) self.painter.setPen(color) self.painter.drawRect(-30, 30, 60, 14) cpustr = QString("%1").arg(self.value) fm = QtGui.QFontMetricsF(self.font()) w = fm.size(Qt.TextSingleLine,cpustr).width() self.painter.setPen(self.foreground) self.painter.drawText(-w / 2, 42, cpustr) self.painter.restore() def drawPointer(self): self.painter.save() self.pointerHand=QPolygon([-2,0, 2,0, 0,60]) self.pointerColor = QColor(127 , 0, 127) self.painter.setBrush(self.pointerColor) self.painter.rotate(self.startAngle) degRotate = (360.0 - self.startAngle - self.endAngle)/(self.maxValue - self.minValue)*(self.value - self.minValue) self.painter.rotate(degRotate) self.painter.drawConvexPolygon(self.pointerHand) self.painter.restore()
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) width = self.width() height = self.height() if self.dynamic_resize: knob_radius = self.dynamic_knob_radius else: knob_radius = self.knob_radius # ensure that the center point is in the middle of a pixel to ensure # that exact vertial and horizantal ticks are drawn exactly 1px wide x = math.floor(width / 2.0) + 0.5 y = math.floor(height / 2.0) + 0.5 if DEBUG: painter.fillRect(0, 0, width, height, Qt.yellow) painter.translate(x, y) if self.knob_style == KnobWidget.STYLE_NEEDLE: r = min(x, y) - 1 painter.setPen(Qt.white) painter.setBrush(Qt.white) painter.drawEllipse(QPoint(0, 0), r, r) angle = self.value_factor * self.total_angle - (self.total_angle / 2.0) # draw base knob or needle spike if self.knob_style == KnobWidget.STYLE_ROUND: painter.setPen(self.border_color) if self.pressed: gradient = QRadialGradient(0, 0, knob_radius) gradient.setColorAt(0, self.base_color_pressed) gradient.setColorAt(0.85, self.base_color) gradient.setColorAt(1, self.base_color) painter.setBrush(gradient) else: painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), knob_radius, knob_radius) elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.save() painter.rotate(angle) painter.setPen(self.needle_color) painter.setBrush(self.needle_color) needle = QPolygonF() needle.append(QPointF(self.needle_base_radius * 0.6, 0)) needle.append(QPointF(0, -knob_radius)) needle.append(QPointF(-self.needle_base_radius * 0.6, 0)) painter.drawPolygon(needle) painter.restore() # draw knob mark or needle base if self.knob_style == KnobWidget.STYLE_ROUND: painter.save() painter.rotate(angle) painter.setPen(QPen(self.mark_color, 2)) painter.drawLine(0, -knob_radius * 0.4, 0, -knob_radius * 0.8) painter.restore() elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.setPen(self.border_color) painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), self.needle_base_radius, self.needle_base_radius) if self.scale_visible: painter.setPen(Qt.black) # draw scale arc if self.scale_arc_visible: painter.drawArc(-knob_radius - self.knob_to_scale, -knob_radius - self.knob_to_scale, knob_radius * 2 + self.knob_to_scale * 2, knob_radius * 2 + self.knob_to_scale * 2, (90 + self.total_angle / 2) * 16, -self.total_angle * 16) # draw scale ticks def value_to_angle(value): return (float(value - self.minimum_value) / self.value_range) * self.total_angle - (self.total_angle / 2.0) value = self.minimum_value while value <= self.maximum_value: angle = value_to_angle(value) painter.save() painter.rotate(value_to_angle(value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_large) if self.scale_text_visible: p = painter.worldTransform().map(QPoint(0, -knob_radius - \ self.knob_to_scale - \ self.tick_size_large - \ self.tick_to_text - \ self.text_radius)) painter.restore() if self.scale_text_visible: if DEBUG: painter.save() painter.setPen(QColor(255, 0, 0, 50)) painter.setBrush(QColor(255, 0, 0, 50)) painter.drawEllipse(QPoint(p.x() - x, p.y() - y), self.text_radius, self.text_radius) painter.restore() painter.drawText(p.x() - x - 30, p.y() - y - 30, 60, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, str(value)) for i in range(1, self.scale_step_divisions): sub_value = value + (float(self.scale_step_size) * i) / self.scale_step_divisions if sub_value > self.maximum_value: break painter.save() painter.rotate(value_to_angle(sub_value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_small) painter.restore() value += self.scale_step_size if self.title_text != None: painter.drawText(-knob_radius, knob_radius - 30, knob_radius * 2, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, self.title_text)
class NetWorkCurveGraph(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.value = 0 self.maxvalue = 2**20 # 1Mb/s self.frontcolor = Qt.red self.axiscolor = Qt.black self.values = [] [self.values.append(0) for i in xrange(10)] self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(200) self.resize(400, 300) def updateValue(self): self.bytes_recv = float(getNettate()) self.value = self.bytes_recv / self.maxvalue * 100 print self.bytes_recv, self.value for i in xrange(9): self.values[i] = self.values[i + 1] self.values[-1] = float(getNettate()) / self.maxvalue * 100 def paintEvent(self, QPaintEvent): self.updateValue() self.painter = QPainter() self.painter.begin(self) self.side = min(self.width(), self.height()) self.axesscale = self.side / 10 * 2 self.histogramscale = self.side - self.axesscale self.drawAxes() self.drawPoints() def drawAxes(self): self.painter.save() self.painter.setPen(self.axiscolor) # draw axes line self.painter.drawLine(self.axesscale / 2, self.height() - self.axesscale / 2, self.axesscale / 2, 0) self.painter.drawLine(self.axesscale / 2, self.height() - self.axesscale / 2, self.width(), self.height() - self.axesscale / 2) #draw y axis num self.yheight = self.height() - self.axesscale / 2 step = self.yheight / 5 for i in xrange(5): lineheight = self.yheight - (i * step) self.painter.drawLine(self.axesscale / 2, lineheight, self.axesscale / 2 + 5, lineheight) numstr = QString("%1 kb/s").arg(i * 250) self.painter.drawText(0, lineheight, numstr) self.painter.restore() def drawPoints(self): self.painter.save() self.painter.setPen(self.frontcolor) self.painter.setBrush(self.frontcolor) width = self.width() - self.axesscale / 2 step = width / 10 for i in xrange(0, 9): point1height = (100 - self.values[i]) * self.yheight / 100 point2height = (100 - self.values[i + 1]) * self.yheight / 100 if (self.values[i] != 0): self.painter.drawLine(width - i * step, point1height, width - (i + 1) * step, point2height) self.painter.restore()
class Chii(QtGui.QWidget): """ Chobits (ちょびっツ Chobittsu?) is a Japanese manga created by the Japanese manga collective Clamp Chi (ちぃ Chii?) is A "chobit" wikipedia : http://en.wikipedia.org/wiki/Chobits """ def __init__(self, parent=None): super(Chii, self).__init__() self.talkdialog = TalkDialog() self.picnames = ["./pictures/chii.png","./pictures/chii2.png"] self.pictures = [] self.current_pic = None self.current_pic_num = 0 self.word = "" self.talkflag = 0 self.initui() def initui(self): self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.load_img() self.createContextMenu() def load_img(self): """function to load pictures """ #add pictures to picture list for picname in self.picnames: self.pictures.append(QPixmap(picname)) self.current_pic = self.pictures[self.current_pic_num] self.width,self.height = self.current_pic.width(),self.current_pic.height() #self.setMask(self.current_pic.mask()) def paintEvent(self, QPaintEvent): self.painter = QPainter() self.painter.begin(self) self.drawImg() self.drawWord() self.resize(self.current_pic.width(),self.current_pic.height()) self.setMask(self.current_pic.mask()) self.painter.end() def drawImg(self): self.painter.save() self.img = QImage(self.current_pic.toImage()) self.pic_rect = QRect(0, 0, self.current_pic.width(), self.current_pic.height()) self.painter.drawImage(self.pic_rect, self.img) self.painter.restore() def drawWord(self): self.painter.save() self.painter.setPen(Qt.black) self.painter.setBrush(Qt.black) if self.talkflag ==1: word = QString(self.word) else: word = "" fm = QtGui.QFontMetricsF(self.font()) w = fm.size(Qt.TextSingleLine,word).width() self.painter.drawText(self.width, 50, word) self.painter.restore() def mousePressEvent(self, QMouseEvent): if QMouseEvent.buttons() == Qt.LeftButton: self.dragPosition = QMouseEvent.globalPos() - self.frameGeometry().topLeft() QMouseEvent.accept() def mouseMoveEvent(self, QMouseEvent): if QMouseEvent.buttons() ==QtCore.Qt.LeftButton: self.move(QMouseEvent.globalPos() - self.dragPosition) QMouseEvent.accept() def createContextMenu(self): self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.showContextMenu) # create QMenu self.contextMenu = QtGui.QMenu(self) self.talk_menu = self.contextMenu.addAction(u'talk') self.status_menu = self.contextMenu.addAction(u'status') self.about_menu = self.contextMenu.addAction(u'about') self.close_menu = self.contextMenu.addAction(u'close') self.talk_menu.triggered.connect(self.talk_action) self.status_menu.triggered.connect(self.status_action) self.about_menu.triggered.connect(self.about_action) self.close_menu.triggered.connect(self.colse_action) def showContextMenu(self, pos): self.contextMenu.move(self.pos() + pos) self.contextMenu.show() def changpic(self): """ change the picture to a picture with textfield""" if self.current_pic_num < len(self.pictures)-1: self.current_pic_num += 1 else: self.current_pic_num = 0 self.current_pic = self.pictures[self.current_pic_num] self.update() def status_action(self): self.changpic() self.talkflag =1 self.word = "CPU : "+str(currentCPU(0))+"%" def talk_action(self): self.talkdialog.show() def colse_action(self): self.talkdialog.close() self.close() def about_action(self): self.msg = QMessageBox(self) self.msg.about(self, "About", "Author:Mithrilwoodrat")
def paintEvent(self, event): """Adapted from http://doc.qt.io/qt-5/qtwidgets-widgets-analogclock-example.html""" HOURHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -55)]) MINUTEHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -87)]) HOURCOLOR = QColor(Qt.black) MINUTECOLOR = QColor(0x11, 0x11, 0x11, 0xAA) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) SIDE = 200 side = min(self.width(), self.height()) painter.scale(side / SIDE, side / SIDE) # Background (night/day) if self._time_to is not None: time = self._time_to.time() hour_offset = time.hour() + time.minute() / 60 DAY, NIGHT = QColor(Qt.white), QColor('#5555ff') if 7 <= hour_offset <= 19: background = DAY elif 6 <= hour_offset <= 7: palette = GradientPaletteGenerator(NIGHT, DAY) background = palette[(hour_offset - 6) / (7 - 6)] elif 19 <= hour_offset <= 20: palette = GradientPaletteGenerator(DAY, NIGHT) background = palette[(hour_offset - 19) / (20 - 19)] else: assert hour_offset < 7 or hour_offset > 20 background = NIGHT painter.setBrush(QBrush(background)) painter.setPen(HOURCOLOR) painter.drawEllipse(-SIDE / 2, -SIDE / 2, SIDE, SIDE) # Minute tickmarks painter.save() painter.setPen(MINUTECOLOR) for j in range(60): painter.drawLine(94, 0, 97, 0) painter.rotate(6) painter.restore() # Hour tickmarks painter.save() painter.setPen(HOURCOLOR) for _ in range(12): painter.drawLine(88, 0, 98, 0) painter.rotate(30) painter.restore() # Hour span if self._time_from is not None: time_from = self._time_from.time() time_to = self._time_to.time() if time_from.secsTo( time_to) / 3600 > .2: # Don't draw really small intervals hour_from = (time_from.hour() + time_from.minute() / 60) % 12 - 3 hour_to = (time_to.hour() + time_to.minute() / 60) % 12 - 3 startAngle = -hour_to * 30 * 16 spanAngle = -hour_from * 30 * 16 - startAngle color = QColor(0xFF, 0xFF, 0, 0xAA) painter.save() painter.setBrush(QBrush(color, Qt.DiagCrossPattern)) painter.setPen(color.darker(180)) painter.drawPie(-SIDE / 2, -SIDE / 2, SIDE, SIDE, startAngle, spanAngle) painter.restore() # Hour and minute hand if self._time_to is not None: time = self._time_to.time() painter.setPen(Qt.NoPen) painter.save() painter.setBrush(HOURCOLOR) painter.rotate(30 * (time.hour() + time.minute() / 60)) painter.drawConvexPolygon(HOURHAND) painter.restore() painter.save() painter.setBrush(MINUTECOLOR) painter.rotate(6 * (time.minute() + time.second() / 60)) painter.drawConvexPolygon(MINUTEHAND) painter.restore()
def paintEvent(self, event): # Initialize QPainter properties painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) if self.height() <= self.width() / self.ref_aspect_ratio: v_scale = self.height() h_scale = v_scale * self.ref_aspect_ratio else: h_scale = self.width() v_scale = h_scale / self.ref_aspect_ratio # Scale all objects proportionate to window size painter.scale(h_scale / self.width_ref, v_scale / self.height_ref) painter.setClipPath(self.dial) # Don't allow objects or text to extend outside of main dial shape painter.save() # First draw main gauge background pen = QPen(painter.pen()) pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(100, 100, 100, 255)) # self.dial_bg) painter.drawPath(self.dial) # Add Minor and Major Alarm limit bars pen.setWidth(16) pen.setCapStyle(Qt.FlatCap) pen.setJoinStyle(Qt.BevelJoin) pen.setColor(Qt.yellow) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(self.low_arc) painter.drawPath(self.high_arc) pen.setColor(Qt.red) painter.setPen(pen) painter.drawPath(self.lolo_arc) painter.drawPath(self.hihi_arc) painter.restore() # Display PV current value painter.save() font = QFont() font.setPixelSize(45) painter.setFont(font) sevr = self.channel.sevr.lower() if sevr == 'major': color = Qt.red elif sevr == 'minor': color = Qt.yellow elif sevr == 'invalid': color = Qt.magenta else: color = Qt.green pen.setColor(color) painter.setPen(pen) font_metric = QFontMetrics(font) painter.translate(self.dial_width / 2, self.dial_height / 2) label = self.format_label(self.channel_value) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, font_metric.height() / 2.0), label) # Display PV name painter.setFont(self.pv_label_font) pen.setColor(Qt.black) # Qt.darkCyan) pen.setWidth(1) painter.setPen(pen) # brush = QBrush(Qt.darkCyan) # painter.setBrush(brush) font_metric = QFontMetrics(self.pv_label_font) pv_label = self.channel.egu # self.channel.name + ' (' + self.channel.egu + ')' painter.drawText(QPointF(0.0 - font_metric.width(pv_label) / 2.0, (self.dial_height / 2.0) + (font_metric.height() * 1.5)), pv_label) # painter.drawPath(self.pv_label_path) painter.restore() # Next add division markers painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) pen.setWidth(2) painter.setPen(pen) for i in range(0, 31): if (i % 5) != 0: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.2, 0.0) else: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.3, 0.0) painter.rotate(6.0) painter.restore() # Layout division text labels painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) painter.setPen(pen) font = QFont() font.setPixelSize(18) painter.setFont(font) font_metric = QFontMetrics(font) labels = linspace(self.lim_low, self.lim_hi, 7) painter.rotate(-90) for i in range(0, 7): label = self.format_label(labels[i]) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, -self.dial_height * 0.75), label) painter.rotate(30) painter.restore() # Draw needle at appropriate angle for data painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.rotate(-180 * (1.0 - self.percentage)) pen.setColor(QColor(self.needle_color).darker(200)) pen.setWidth(1) painter.setPen(pen) painter.setBrush(self.needle_color) painter.drawPolygon(self.needle) painter.restore() # if self.percentage <= 0.5: # shadow = max(490 * self.percentage, 127) # needle_left_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # needle_right_color = Qt.cyan # QColor(230,230,230,255) # else: # shadow = max(125 / self.percentage, 127) # needle_left_color = Qt.cyan # QColor(230,230,230,255) # needle_right_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # # # Draw Highlight side of needle # pen.setWidth(1) # pen.setColor(Qt.gray) # needle_left_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_left_color) # painter.drawPolygon(self.needle_left) # # # Draw shadow side of needle # pen.setColor(Qt.gray) # needle_right_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_right_color) # painter.drawPolygon(self.needle_right) # painter.restore() # Draw needle axel pin painter.save() pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(50, 50, 50, 255)) # self.pin_bg) painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.drawEllipse(self.pin_rect) painter.restore() # Draw glass reflection and shadow effects # painter.save() # painter.translate(self.dial_width / 2.0, self.dial_height / 2.0) # painter.setPen(Qt.NoPen) # painter.setBrush(QColor(0, 0, 0, 20)) # painter.drawEllipse(self.shadow_rect) # painter.setBrush(self.gloss_gradient) # painter.drawEllipse(self.gloss_rect) # painter.restore() painter.end()
def drawImage(self, imageid): cache = image_cache.cache cellColoring = self.cellColoring wallColoring = self.wallColoring pointColoring = self.pointColoring ellipsisDraw = self.ellipsisDraw overSampling = self.overSampling extraDrawing = self.extraDrawing bgColor = self.bgColor.rgb() result = self.result if self.result_type == "Data": data = result img_name = result.images_name[imageid] else: data = result.data img_name = result.images[imageid] #scale = data.images_scale[img_name] min_scale = data.minScale() img = cache.image(data.image_path(img_name)) img_data = data[img_name] size = self._crop.size() pix = QImage(size*overSampling, QImage.Format_ARGB32) pix.fill(bgColor) painter = QPainter() if not painter.begin(pix): self.abort("Cannot create painter on QImage") return None, None, None painter.setRenderHints(QPainter.SmoothPixmapTransform, True) painter.setRenderHints(QPainter.Antialiasing, True) if overSampling > 1: painter.scale(overSampling, overSampling) painter.translate(-self._crop.topLeft()) painter.save() painter.translate(self.translate) log_debug("Translating: %gx%g" % (self.translate.x(), self.translate.y()) ) painter.scale(1/min_scale, 1/min_scale) painter.save() matrix = img_data.matrix() painter.setWorldTransform(matrix, True) painter.drawImage(QPoint(0,0), img) painter.restore() #pt_matrix = QTransform() #pt_matrix.scale(1/min_scale, 1/min_scale) #painter.setTransform(pt_matrix, True) cellColoring.startImage(painter, imageid) wallColoring.startImage(painter, imageid) for ed in extraDrawing: ed.startImage(painter, imageid) if self.result_type == "Growth": cells = result.cells[imageid] walls = result.walls[imageid] else: cells = img_data.cells walls = set() for cid in img_data.cells: pts = [ pt for pt in data.cells[cid] if pt in img_data ] if len(pts) > 1: for i in range(len(pts)): walls.add(data.wallId(pts[i-1], pts[i])) # Now, draw the cells and the ellipsis for cid in cells: painter.setPen(Qt.NoPen) color = cellColoring(imageid, cid) painter.setBrush(color) pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1,p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1,p2]) ppts.append(ppts[0]) poly = QPolygonF(ppts) painter.drawPolygon(poly) # And draw the walls wallThickness = self.wallThickness*min_scale for wid in walls: color = wallColoring(imageid, wid) if color.alpha() > 0: pen = QPen(color) pen.setWidthF(wallThickness) painter.setPen(pen) pts = [img_data[wid[0]]] + img_data.walls[wid[0], wid[1]] + [img_data[wid[1]]] #painter.drawLine(img_data[wid[0]], img_data[wid[1]]) painter.drawPolyline(*pts) # Then, draw the points pointSize = self.pointSize*min_scale pointLineColor = self.pointLineColor pointLineThickness = self.pointLineThickness*min_scale log_debug("pointSize = %g" % pointSize) for pid in img_data: color = pointColoring(imageid, pid) if color.alpha() > 0: pen = QPen(pointLineColor) pen.setWidthF(pointLineThickness) brush = QBrush(color) painter.setPen(pen) painter.setBrush(brush) pos = img_data[pid] rect = QRectF(pos.x()-pointSize, pos.y()-pointSize, 2*pointSize, 2*pointSize) painter.drawEllipse(rect) if ellipsisDraw.plot: for cid in cells: pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1,p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1,p2]) ppts.append(ppts[0]) #poly = QPolygonF(ppts) #painter.drawPolygon(poly) ellipsisDraw(painter, imageid, cid, ppts, min_scale) # At last, draw the extra data for ed in extraDrawing: ed(painter, imageid) tr = painter.worldTransform() painter.restore() pic_w = wallColoring.finalizeImage(painter, imageid, tr, self.crop) pic_c = cellColoring.finalizeImage(painter, imageid, tr, self.crop) for ed in extraDrawing: ed.finalizeImage(painter, imageid, tr, self.crop) painter.end() return pix, pic_w, pic_c
def imprimir(self,printer): leftMargin = 72 widthCol = 100 arialFont = QFont("Helvetica",16,3) fuente =QFontMetrics(arialFont) arialLineHeight = fuente.height() fondo = QPixmap(":/images/res/fondo.png") painter = QPainter(printer) pageRect = printer.pageRect() page = 1 painter.save() if self.vistaprevia: painter.drawPixmap(0, 0, 530, 830, fondo) painter.setFont(arialFont) y = 180 x = 35 painter.drawText(x,y,self.editmodel.fecha.toString("dd MM yy")) y = 210 x = 85 painter.drawText(x,y, self.editmodel.cliente) painter.setFont(arialFont) cajasFont = QFont("Helvetica",10,2) x = -5 y = 295 painter.setFont(cajasFont) painter.drawText(x,y - arialLineHeight - 1,"Cajas") for row in self.editmodel.lines: painter.setFont(cajasFont) x = 2 painter.drawText(x,y,row.cantidad()) painter.setFont(arialFont) total = moneyfmt(row.total,2,"") x = 470 - fuente.width(total) painter.drawText(x,y,total) x =310 painter.drawText(x,y,moneyfmt(row.itemPrice,2,"")) x = 30 painter.drawText(x,y,row.unidades()) x = 80 painter.drawText(x,y,row.itemDescription) y+= arialLineHeight total = moneyfmt(self.editmodel.total,2,"") y= 690 x = 470 - fuente.width(total) painter.drawText(x,y,total) painter.setPen(Qt.black) # printer.newPage() painter.restore()
def paintEvent(self, event): painter = QPainter(self) width = self.width() height = self.height() if self.scales_visible: curve_width = width - self.y_scale.total_width - self.curve_to_scale - self.curve_outer_border curve_height = height - self.y_scale_height_offset - self.x_scale.total_height - self.curve_to_scale else: curve_width = width - self.curve_outer_border - self.curve_outer_border curve_height = height - self.curve_outer_border - self.curve_outer_border if DEBUG: painter.fillRect(0, 0, width, height, Qt.green) # fill canvas if self.scales_visible: canvas_x = self.y_scale.total_width + self.curve_to_scale - self.curve_outer_border canvas_y = self.y_scale_height_offset - self.curve_outer_border else: canvas_x = 0 canvas_y = 0 canvas_width = self.curve_outer_border + curve_width + self.curve_outer_border canvas_height = self.curve_outer_border + curve_height + self.curve_outer_border painter.fillRect(canvas_x, canvas_y, canvas_width, canvas_height, self.canvas_color) # draw cross hair at cursor position if self.cross_hair_visible: p = self.mapFromGlobal(QCursor.pos()) p_x = p.x() p_y = p.y() if p_x >= canvas_x and p_x < canvas_x + canvas_width and \ p_y >= canvas_y and p_y < canvas_y + canvas_height: painter.setPen(QPen(QColor(190, 190, 190), 1, Qt.DashLine)) painter.drawLine(canvas_x, p_y, canvas_x + canvas_width - 1, p_y) painter.drawLine(p_x, canvas_y, p_x, canvas_y + canvas_height - 1) # draw canvas border if self.curve_outer_border > 0: painter.setPen(QColor(190, 190, 190)) painter.drawRect(canvas_x, canvas_y, canvas_width - 1, canvas_height - 1) # -1 to accommodate the 1px width of the border painter.setPen(Qt.black) if DEBUG: painter.fillRect(canvas_x + self.curve_outer_border, canvas_y + self.curve_outer_border, curve_width, curve_height, Qt.cyan) # draw scales y_min_scale = self.y_scale.value_min y_max_scale = self.y_scale.value_max factor_x = float(curve_width) / self.history_length_x factor_y = float(curve_height - 1) / max(y_max_scale - y_min_scale, EPSILON) # -1 to accommodate the 1px width of the curve if self.scales_visible: self.draw_x_scale(painter, factor_x) self.draw_y_scale(painter, curve_height, factor_y) # draw curves if self.x_min != None and self.x_max != None: x_min = self.x_min x_max = self.x_max if self.scales_visible: curve_x_offset = 0 else: curve_x_offset = round((self.history_length_x - (x_max - x_min)) * factor_x) painter.save() painter.translate(canvas_x + self.curve_outer_border + curve_x_offset, canvas_y + self.curve_outer_border + curve_height - 1 + self.curve_y_offset) # -1 to accommodate the 1px width of the curve painter.scale(factor_x, -factor_y) painter.translate(-x_min, -y_min_scale) for c in range(len(self.curves_x)): if not self.curves_visible[c]: continue curve_x = self.curves_x[c] curve_y = self.curves_y[c] path = QPainterPath() lineTo = path.lineTo path.moveTo(curve_x[0], curve_y[0]) for i in xrange(1, len(curve_x)): lineTo(curve_x[i], curve_y[i]) painter.setPen(self.plots[c][1]) painter.drawPath(path) painter.restore()
def paintEvent( self, event ): # Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern. frameWidth = 16 dotCenter = QPoint( 0, 0 ) shiftCenter = dotCenter # Damit der Rahmen nicht irgendwie abgeschnitten wird, muß der Kreis entsprechend kleiner sein. dotRadius = 100 framePen = QPen() framePen.setWidth(frameWidth ) framePen.setColor( self._colorFrame ) dotDiameter = 2 * dotRadius + frameWidth painter = QPainter( self ) windowWidth = self.width() // self.maximum windowHeight = float( self.height() ) side = min( windowWidth, windowHeight ) painter.setRenderHint( QPainter.Antialiasing ) if ( not self.isEnabled() ): painter.setOpacity( .5 ) painter.translate( side / 2, self.height() / 2 ) painter.scale( side / dotDiameter, side / dotDiameter ) painter.setPen( framePen ) painter.setBrush( self._colorFull ) painter.save() for i in range(self.value): shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 ) painter.drawEllipse( shiftCenter, dotRadius, dotRadius ) ## if (v_forbiddenValues.contains(i+1)){ ## painter.drawEllipse(shiftCenter, dotRadius/2, dotRadius/2); painter.restore() painter.setBrush( QColor(Config.COLOR_BONUS) ) painter.save() for i in range(self.value, self.value + self.__bonusValue): shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 ) painter.drawEllipse( shiftCenter, dotRadius, dotRadius ) painter.restore() painter.setBrush( self._colorEmpty ) painter.save() for i in range(self.value + self.__bonusValue, self.maximum): shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 ) painter.drawEllipse( shiftCenter, dotRadius, dotRadius ) j = i+1 if ( j in self.forbiddenValues ): dotRadiusHalf = dotRadius / 2 painter.drawLine( shiftCenter.x() - dotRadiusHalf, shiftCenter.y() - dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() + dotRadiusHalf ) painter.drawLine( shiftCenter.x() - dotRadiusHalf, shiftCenter.y() + dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() - dotRadiusHalf ) painter.restore()
def drawImage(self, imageid): cache = image_cache.cache cellColoring = self.cellColoring wallColoring = self.wallColoring pointColoring = self.pointColoring ellipsisDraw = self.ellipsisDraw overSampling = self.overSampling extraDrawing = self.extraDrawing bgColor = self.bgColor.rgb() result = self.result if self.result_type == "Data": data = result img_name = result.images_name[imageid] else: data = result.data img_name = result.images[imageid] #scale = data.images_scale[img_name] min_scale = data.minScale() img = cache.image(data.image_path(img_name)) img_data = data[img_name] size = self._crop.size() pix = QImage(size * overSampling, QImage.Format_ARGB32) pix.fill(bgColor) painter = QPainter() if not painter.begin(pix): self.abort("Cannot create painter on QImage") return None, None, None painter.setRenderHints(QPainter.SmoothPixmapTransform, True) painter.setRenderHints(QPainter.Antialiasing, True) if overSampling > 1: painter.scale(overSampling, overSampling) painter.translate(-self._crop.topLeft()) painter.save() painter.translate(self.translate) log_debug("Translating: %gx%g" % (self.translate.x(), self.translate.y())) painter.scale(1 / min_scale, 1 / min_scale) painter.save() matrix = img_data.matrix() painter.setWorldTransform(matrix, True) painter.drawImage(QPoint(0, 0), img) painter.restore() #pt_matrix = QTransform() #pt_matrix.scale(1/min_scale, 1/min_scale) #painter.setTransform(pt_matrix, True) cellColoring.startImage(painter, imageid) wallColoring.startImage(painter, imageid) for ed in extraDrawing: ed.startImage(painter, imageid) if self.result_type == "Growth": cells = result.cells[imageid] walls = result.walls[imageid] else: cells = img_data.cells walls = set() for cid in img_data.cells: pts = [pt for pt in data.cells[cid] if pt in img_data] if len(pts) > 1: for i in range(len(pts)): walls.add(data.wallId(pts[i - 1], pts[i])) # Now, draw the cells and the ellipsis for cid in cells: painter.setPen(Qt.NoPen) color = cellColoring(imageid, cid) painter.setBrush(color) pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1, p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1, p2]) ppts.append(ppts[0]) poly = QPolygonF(ppts) painter.drawPolygon(poly) # And draw the walls wallThickness = self.wallThickness * min_scale for wid in walls: color = wallColoring(imageid, wid) if color.alpha() > 0: pen = QPen(color) pen.setWidthF(wallThickness) painter.setPen(pen) pts = [img_data[wid[0]] ] + img_data.walls[wid[0], wid[1]] + [img_data[wid[1]]] #painter.drawLine(img_data[wid[0]], img_data[wid[1]]) painter.drawPolyline(*pts) # Then, draw the points pointSize = self.pointSize * min_scale pointLineColor = self.pointLineColor pointLineThickness = self.pointLineThickness * min_scale log_debug("pointSize = %g" % pointSize) for pid in img_data: color = pointColoring(imageid, pid) if color.alpha() > 0: pen = QPen(pointLineColor) pen.setWidthF(pointLineThickness) brush = QBrush(color) painter.setPen(pen) painter.setBrush(brush) pos = img_data[pid] rect = QRectF(pos.x() - pointSize, pos.y() - pointSize, 2 * pointSize, 2 * pointSize) painter.drawEllipse(rect) if ellipsisDraw.plot: for cid in cells: pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1, p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1, p2]) ppts.append(ppts[0]) #poly = QPolygonF(ppts) #painter.drawPolygon(poly) ellipsisDraw(painter, imageid, cid, ppts, min_scale) # At last, draw the extra data for ed in extraDrawing: ed(painter, imageid) tr = painter.worldTransform() painter.restore() pic_w = wallColoring.finalizeImage(painter, imageid, tr, self.crop) pic_c = cellColoring.finalizeImage(painter, imageid, tr, self.crop) for ed in extraDrawing: ed.finalizeImage(painter, imageid, tr, self.crop) painter.end() return pix, pic_w, pic_c
def __paintEventNoStyle(self): p = QPainter(self) opt = QStyleOptionToolButton() self.initStyleOption(opt) fm = QFontMetrics(opt.font) palette = opt.palette # highlight brush is used as the background for the icon and background # when the tab is expanded and as mouse hover color (lighter). brush_highlight = palette.highlight() if opt.state & QStyle.State_Sunken: # State 'down' pressed during a mouse press (slightly darker). background_brush = brush_darker(brush_highlight, 110) elif opt.state & QStyle.State_MouseOver: background_brush = brush_darker(brush_highlight, 95) elif opt.state & QStyle.State_On: background_brush = brush_highlight else: # The default button brush. background_brush = palette.button() rect = opt.rect icon = opt.icon icon_size = opt.iconSize # TODO: add shift for pressed as set by the style (PM_ButtonShift...) pm = None if not icon.isNull(): if opt.state & QStyle.State_Enabled: mode = QIcon.Normal else: mode = QIcon.Disabled pm = opt.icon.pixmap( rect.size().boundedTo(icon_size), mode, QIcon.On if opt.state & QStyle.State_On else QIcon.Off) icon_area_rect = QRect(rect) icon_area_rect.setRight(int(icon_area_rect.height() * 1.26)) text_rect = QRect(rect) text_rect.setLeft(icon_area_rect.right() + 10) # Background (TODO: Should the tab button have native # toolbutton shape, drawn using PE_PanelButtonTool or even # QToolBox tab shape) # Default outline pen pen = QPen(palette.color(QPalette.Mid)) p.save() p.setPen(Qt.NoPen) p.setBrush(QBrush(background_brush)) p.drawRect(rect) # Draw the background behind the icon if the background_brush # is different. if not opt.state & QStyle.State_On: p.setBrush(brush_highlight) p.drawRect(icon_area_rect) # Line between the icon and text p.setPen(pen) p.drawLine(icon_area_rect.topRight(), icon_area_rect.bottomRight()) if opt.state & QStyle.State_HasFocus: # Set the focus frame pen and draw the border pen = QPen(QColor(FOCUS_OUTLINE_COLOR)) p.setPen(pen) p.setBrush(Qt.NoBrush) # Adjust for pen rect = rect.adjusted(0, 0, -1, -1) p.drawRect(rect) else: p.setPen(pen) # Draw the top/bottom border if self.position == QStyleOptionToolBoxV2.OnlyOneTab or \ self.position == QStyleOptionToolBoxV2.Beginning or \ self.selected & \ QStyleOptionToolBoxV2.PreviousIsSelected: p.drawLine(rect.topLeft(), rect.topRight()) p.drawLine(rect.bottomLeft(), rect.bottomRight()) p.restore() p.save() text = fm.elidedText(opt.text, Qt.ElideRight, text_rect.width()) p.setPen(QPen(palette.color(QPalette.ButtonText))) p.setFont(opt.font) p.drawText(text_rect, int(Qt.AlignVCenter | Qt.AlignLeft) | \ int(Qt.TextSingleLine), text) if pm: pm_rect = QRect(QPoint(0, 0), pm.size()) centered_rect = QRect(pm_rect) centered_rect.moveCenter(icon_area_rect.center()) p.drawPixmap(centered_rect, pm, pm_rect) p.restore()
class HdHistogram(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.value = 0 self.frontcolor = Qt.blue self.axiscolor = Qt.black self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(200) self.values = [] [self.values.append(getHdstate()) for i in xrange(10)] self.resize(400, 300) def updateValue(self): self.value = getHdstate() for i in xrange(9): self.values[i] = self.values[i + 1] self.values[-1] = getHdstate() for i in xrange(10): print(self.values[i]) def paintEvent(self, QPaintEvent): self.updateValue() self.painter = QPainter() self.painter.begin(self) self.side = min(self.width(), self.height()) self.axesscale = self.side / 10 * 2 self.histogramscale = self.side - self.axesscale self.drawAxes() self.drawRect() def drawAxes(self): self.painter.save() self.painter.setPen(self.axiscolor) #draw axes line self.painter.drawLine(self.axesscale / 2, self.height() - self.axesscale / 2, self.axesscale / 2, 0) self.painter.drawLine(self.axesscale / 2, self.height() - self.axesscale / 2, self.width(), self.height() - self.axesscale / 2) #draw y axis num self.yheight = self.height() - self.axesscale / 2 step = self.yheight / 11 for i in xrange(11): lineheight = self.yheight - (i * step) self.painter.drawLine(self.axesscale / 2, lineheight, self.axesscale / 2 + 5, lineheight) numstr = QString("%1%").arg(i * 10) self.painter.drawText(0, lineheight, numstr) self.painter.restore() def drawRect(self): self.painter.save() self.painter.setPen(self.frontcolor) self.painter.setBrush(self.frontcolor) width = self.width() - self.axesscale / 2 step = width / 10 for i in xrange(0, 10): rectheight = (self.values[i] / 100) * self.yheight self.painter.drawRect(width - step * i, self.yheight - rectheight, step, rectheight) self.painter.restore()
def paintEvent(self, event): """Adapted from http://doc.qt.io/qt-5/qtwidgets-widgets-analogclock-example.html""" HOURHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -55)]) MINUTEHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -87)]) HOURCOLOR = QColor(Qt.black) MINUTECOLOR = QColor(0x11, 0x11, 0x11, 0xAA) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) SIDE = 200 side = min(self.width(), self.height()) painter.scale(side / SIDE, side / SIDE) # Background (night/day) if self._time_to is not None: time = self._time_to.time() hour_offset = time.hour() + time.minute() / 60 DAY, NIGHT = QColor(Qt.white), QColor('#5555ff') if 7 <= hour_offset <= 19: background = DAY elif 6 <= hour_offset <= 7: palette = GradientPaletteGenerator(NIGHT, DAY) background = palette[(hour_offset - 6) / (7 - 6)] elif 19 <= hour_offset <= 20: palette = GradientPaletteGenerator(DAY, NIGHT) background = palette[(hour_offset - 19) / (20 - 19)] else: assert hour_offset < 7 or hour_offset > 20 background = NIGHT painter.setBrush(QBrush(background)) painter.setPen(HOURCOLOR) painter.drawEllipse(-SIDE / 2, -SIDE / 2, SIDE, SIDE) # Minute tickmarks painter.save() painter.setPen(MINUTECOLOR) for j in range(60): painter.drawLine(94, 0, 97, 0) painter.rotate(6) painter.restore() # Hour tickmarks painter.save() painter.setPen(HOURCOLOR) for _ in range(12): painter.drawLine(88, 0, 98, 0) painter.rotate(30) painter.restore() # Hour span if self._time_from is not None: time_from = self._time_from.time() time_to = self._time_to.time() if time_from.secsTo(time_to) / 3600 > .2: # Don't draw really small intervals hour_from = (time_from.hour() + time_from.minute() / 60) % 12 - 3 hour_to = (time_to.hour() + time_to.minute() / 60) % 12 - 3 startAngle = -hour_to * 30 * 16 spanAngle = -hour_from * 30 * 16 - startAngle color = QColor(0xFF, 0xFF, 0, 0xAA) painter.save() painter.setBrush(QBrush(color, Qt.DiagCrossPattern)) painter.setPen(color.darker(180)) painter.drawPie(-SIDE / 2, -SIDE / 2, SIDE, SIDE, startAngle, spanAngle) painter.restore() # Hour and minute hand if self._time_to is not None: time = self._time_to.time() painter.setPen(Qt.NoPen) painter.save() painter.setBrush(HOURCOLOR) painter.rotate(30 * (time.hour() + time.minute() / 60)) painter.drawConvexPolygon(HOURHAND) painter.restore() painter.save() painter.setBrush(MINUTECOLOR) painter.rotate(6 * (time.minute() + time.second() / 60)) painter.drawConvexPolygon(MINUTEHAND) painter.restore()
def imprimir(self, printer): leftMargin = 72 widthCol = 100 arialFont = QFont("Helvetica", 16, 3) fuente = QFontMetrics(arialFont) arialLineHeight = fuente.height() fondo = QPixmap(":/images/res/fondo.png") painter = QPainter(printer) pageRect = printer.pageRect() page = 1 painter.save() if self.vistaprevia: painter.drawPixmap(0, 0, 530, 830, fondo) painter.setFont(arialFont) y = 180 x = 35 painter.drawText(x, y, self.editmodel.fecha.toString("dd MM yy")) y = 210 x = 85 painter.drawText(x, y, self.editmodel.cliente) painter.setFont(arialFont) cajasFont = QFont("Helvetica", 10, 2) x = -5 y = 295 painter.setFont(cajasFont) painter.drawText(x, y - arialLineHeight - 1, "Cajas") for row in self.editmodel.lines: painter.setFont(cajasFont) x = 2 painter.drawText(x, y, row.cantidad()) painter.setFont(arialFont) total = moneyfmt(row.total, 2, "") x = 470 - fuente.width(total) painter.drawText(x, y, total) x = 310 painter.drawText(x, y, moneyfmt(row.itemPrice, 2, "")) x = 30 painter.drawText(x, y, row.unidades()) x = 80 painter.drawText(x, y, row.itemDescription) y += arialLineHeight total = moneyfmt(self.editmodel.total, 2, "") y = 690 x = 470 - fuente.width(total) painter.drawText(x, y, total) painter.setPen(Qt.black) # printer.newPage() painter.restore()