def paintEvent(self, event): """ Called when the widget is painted on the window. """ dpr = self.devicePixelRatioF() buffer = QPixmap(self.width() * dpr, self.height() * dpr) buffer.setDevicePixelRatio(dpr) buffer.fill(Qt.transparent) painter = QPainter(buffer) region = QRegion( QRect(0, 0, self._textWidget.sizeHint().width(), self._textWidget.sizeHint().height())) self._textWidget.render(painter, QPoint(0, 0), region) region = QRegion( QRect(0, 0, self._iconWidget.sizeHint().width(), self._iconWidget.sizeHint().height())) x = self._textWidget.sizeHint().width() + 3 self._iconWidget.render(painter, QPoint(x, 0), region) painter.end() painter = QPainter(self) painter.drawPixmap(event.rect(), buffer, buffer.rect()) painter.end()
def __init__(self, parent=None): super(CuriWidget, self).__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint) self.addCustomAction() w = qApp.desktop().screenGeometry().width() h = qApp.desktop().screenGeometry().height() side = round((8 / 9) * min(w / cols, h / rows)) self.setFixedSize(side * QSize(cols, rows)) self.thread = SoundThread(self) self.dragPosition = QPoint() self.button = None self.setWindowIcon(QIcon(":curielements")) region = QRegion(QRect(0, 0, 2 * side, 2 * side), QRegion.Ellipse) region += QRegion(QRect(side, 0, 8 * side, 15 * side)) region += QRegion(QRect(0, side, side, 13 * side)) region += QRegion(QRect(0, 13 * side, 2 * side, 2 * side), QRegion.Ellipse) region += QRegion(QRect(9 * side, side, side, 14 * side)) region += QRegion(QRect(8 * side, 0, 2 * side, 2 * side), QRegion.Ellipse) region += QRegion(QRect(10 * side, 2 * side, 19 * side, 13 * side)) region += QRegion(QRect(28 * side, 2 * side, 2 * side, 2 * side), QRegion.Ellipse) region += QRegion(QRect(29 * side, 3 * side, side, 11 * side)) region += QRegion(QRect(28 * side, 13 * side, 2 * side, 2 * side), QRegion.Ellipse) self.setMask(region) self.atoms = Atoms(self) self.atoms.setGeometry( QRect(1.5 * side, 1.5 * side, 7 * side, 7 * side)) offset = QPoint(10 * side, 3 * side) file = QFile(":elements") file.open(QFile.ReadOnly | QFile.Text) colors = [blue, yellow] self.btns = [] while not file.atEnd(): x, y, name, symbol, electron, description, description2, _ = file.readLine( ).split(',') coordinate = QPoint(int(x), int(y)) text = bytearray(name).decode() btn = ElementButton(QSize(side, side), colors, int(electron), bytearray(symbol).decode(), text, self) btn.move(offset + coordinate * side) btn.clicked.connect(self.button_clicked) self.btns.append(btn) self.imageDescription = DescriptionButton(side * QSize(7, 4.5), blue, self) self.imageDescription.move(1.5 * side, 9 * side) btnSound = DescriptionButton(side * QSize(2, 2), blue, self) btnSound.move(11 * side, 12 * side) btnSound.updateBackground(":soundOn") btnSound.clicked.connect(self.sound_clicled)
def doPaint(self, flags=0): preview = self.mPreviewLayer if not preview: return QRegion() # This method shouldn't be called when current layer is not a tile layer tileLayer = self.currentTileLayer() if (not tileLayer.bounds().intersects( QRect(preview.x(), preview.y(), preview.width(), preview.height()))): return QRegion() paint = PaintTileLayer(self.mapDocument(), tileLayer, preview.x(), preview.y(), preview) if not self.mMissingTilesets.isEmpty(): for tileset in self.mMissingTilesets: AddTileset(self.mapDocument(), tileset, paint) self.mMissingTilesets.clear() paint.setMergeable(flags & PaintFlags.Mergeable) self.mapDocument().undoStack().push(paint) editedRegion = preview.region() if (not (flags & PaintFlags.SuppressRegionEdited)): self.mapDocument().emitRegionEdited(editedRegion, tileLayer) return editedRegion
def paint(self, page, painter, rect, callback=None): """Reimplemented to paint all the sub pages on top of each other.""" # make the call back return with the original page, not the overlay page newcallback = CallBack(callback, page) if callback else None # get the device pixel ratio to paint for try: ratio = painter.device().devicePixelRatioF() except AttributeError: ratio = painter.device().devicePixelRatio() pixmaps = [] covered = QRegion() for p, overlayrect in page.visiblePagesAt(rect): pixmap = QPixmap(overlayrect.size() * ratio) if not pixmap.isNull(): pixmap.setDevicePixelRatio(ratio) pt = QPainter(pixmap) pt.translate(p.pos() - overlayrect.topLeft()) p.paint(pt, overlayrect.translated(-p.pos()), newcallback) pt.end() # even an empty pixmap is appended, otherwise the layer count when # compositing goes awry pos = overlayrect.topLeft() pixmaps.append((pos, pixmap)) covered += overlayrect if QRegion(rect).subtracted(covered): painter.fillRect(rect, page.paperColor or self.paperColor) self.combine(painter, pixmaps)
def itemRegion(self, index): if not index.isValid(): return QRegion() if index.column() != 1: return QRegion(self.itemRect(index)) if self.model().data(index) <= 0.0: return QRegion() startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): sliceIndex = self.model().index(row, 1, self.rootIndex()) value = self.model().data(sliceIndex) if value > 0.0: angle = 360 * value / self.totalValue if sliceIndex == index: slicePath = QPainterPath() slicePath.moveTo(self.totalSize / 2, self.totalSize / 2) slicePath.arcTo(self.margin, self.margin, self.margin + self.pieSize, self.margin + self.pieSize, startAngle, angle) slicePath.closeSubpath() return QRegion(slicePath.toFillPolygon().toPolygon()) startAngle += angle return QRegion()
def draw(self, painter: QPainter): assert self.crop, 'crop must be set' # Compute painter regions for the crop and the blur all_region = QRegion(painter.viewport()) crop_region = QRegion(self.crop) blur_region = all_region.subtracted(crop_region) # Let the QGraphicsBlurEffect only paint in blur_region painter.setClipRegion(blur_region) # Fill with black and set opacity so that the blurred region is drawn darker if self.BLUR_DARKEN > 0.0: painter.fillRect(painter.viewport(), Qt.black) painter.setOpacity(1 - self.BLUR_DARKEN) # Draw the blur effect super().draw(painter) # Restore clipping and opacity painter.setClipping(False) painter.setOpacity(1.0) # Get the source pixmap pixmap, offset = self.sourcePixmap(Qt.DeviceCoordinates, QGraphicsEffect.NoPad) painter.setWorldTransform(QTransform()) # Get the source by adding the offset to the crop location source = self.crop if self.CROP_OFFSET_ENABLED: source = source.translated(self.CROP_OFFSET) painter.drawPixmap(self.crop.topLeft() + offset, pixmap, source)
def __updateGeometry(self): """ Update the shadow geometry to fit the widget's changed geometry. """ widget = self.__widget parent = self.__widgetParent radius = self.radius_ pos = widget.pos() if parent != widget.parentWidget(): pos = widget.parentWidget().mapTo(parent, pos) geom = QRect(pos, widget.size()) geom.adjust(-radius, -radius, radius, radius) if geom != self.geometry(): self.setGeometry(geom) # Set the widget mask (punch a hole through to the `widget` instance. rect = self.rect() mask = QRegion(rect) transparent = QRegion(rect.adjusted(radius, radius, -radius, -radius)) mask = mask.subtracted(transparent) self.setMask(mask)
def setupRuleList(self): combinedRegions = coherentRegions(self.mLayerInputRegions.region() + self.mLayerOutputRegions.region()) combinedRegions = QList( sorted(combinedRegions, key=lambda x: x.y(), reverse=True)) rulesInput = coherentRegions(self.mLayerInputRegions.region()) rulesOutput = coherentRegions(self.mLayerOutputRegions.region()) for i in range(combinedRegions.size()): self.mRulesInput.append(QRegion()) self.mRulesOutput.append(QRegion()) for reg in rulesInput: for i in range(combinedRegions.size()): if (reg.intersects(combinedRegions[i])): self.mRulesInput[i] += reg break for reg in rulesOutput: for i in range(combinedRegions.size()): if (reg.intersects(combinedRegions[i])): self.mRulesOutput[i] += reg break for i in range(self.mRulesInput.size()): checkCoherent = self.mRulesInput.at(i).united( self.mRulesOutput.at(i)) coherentRegions(checkCoherent).length() == 1 return True
def mask_label_region(self): """ Mask the webcam label region to avoid mouse events :return: """ region = QRegion(self.webcamDisplayLabel.frameGeometry()) region -= QRegion(self.webcamDisplayLabel.geometry()) region += self.webcamDisplayLabel.childrenRegion() self.webcamDisplayLabel.setMask(region)
def setCells(self, x, y, layer, mask=QRegion()): # Determine the overlapping area area = QRegion(QRect(x, y, layer.width(), layer.height())) area &= QRect(0, 0, self.width(), self.height()) if (not mask.isEmpty()): area &= mask for rect in area.rects(): for _x in range(rect.left(), rect.right() + 1): for _y in range(rect.top(), rect.bottom() + 1): self.setCell(_x, _y, layer.cellAt(_x - x, _y - y))
def update_cursor_blocks(self): # Update the areas of the previously selected and currently selected blocks in the editor to avoid artifacts block = self.textCursor().block() if self._last_selected_block: currentBlockRect = self.document().documentLayout( ).blockBoundingRect(block).toRect() lastBlockRect = self.document().documentLayout().blockBoundingRect( self._last_selected_block).toRect() viewportoffset = self.verticalScrollBar().value() currentBlockRect.moveTop(currentBlockRect.y() - viewportoffset) lastBlockRect.moveTop(lastBlockRect.y() - viewportoffset) region = QRegion(currentBlockRect).united(QRegion(lastBlockRect)) self.viewport().update(region) self._last_selected_block = block
def doErase(self, continuation): tileLayer = self.currentTileLayer() tilePos = self.tilePosition() eraseRegion = QRegion(tilePos.x(), tilePos.y(), 1, 1) if (continuation): for p in pointsOnLine(self.mLastTilePos, tilePos): eraseRegion |= QRegion(p.x(), p.y(), 1, 1) self.mLastTilePos = self.tilePosition() if (not tileLayer.bounds().intersects(eraseRegion.boundingRect())): return erase = EraseTiles(self.mapDocument(), tileLayer, eraseRegion) erase.setMergeable(continuation) self.mapDocument().undoStack().push(erase) self.mapDocument().emitRegionEdited(eraseRegion, tileLayer)
def resizeEvent(self, event): super(RoundImageWidget, self).resizeEvent(event) width = self._imageLabel.width() height = self._imageLabel.height() radius = min(width, height) / 10 / 2 verticalRegion = QRegion(0, radius, width, height - 2 * radius) horizontalRegion = QRegion(radius, 0, width - 2 * radius, height) circle = QRegion(0, 0, 2 * radius, 2 * radius, QRegion.Ellipse) region = verticalRegion.united(horizontalRegion) region = region.united(circle) region = region.united(circle.translated(width - 2 * radius, 0)) region = region.united( circle.translated(width - 2 * radius, height - 2 * radius)) region = region.united(circle.translated(0, height - 2 * radius)) self._imageLabel.setMask(region)
def removeTab(self, index): """ Remove a tab at `index`. """ if index >= 0 and index < self.count(): tab = self.__tabs.pop(index) layout_index = self.layout().indexOf(tab.button) if layout_index != -1: self.layout().takeAt(layout_index) self.__group.removeButton(tab.button) tab.button.removeEventFilter(self) if tab.button is self.__sloppyButton: self.__sloppyButton = None self.__sloppyRegion = QRegion() tab.button.deleteLater() tab.button.setParent(None) if self.currentIndex() == index: if self.count(): self.setCurrentIndex(max(index - 1, 0)) else: self.setCurrentIndex(-1)
def __updateCurve(self): curveData = self.__d_curve.data() curveData.values().lock() numPoints = curveData.size() if ( numPoints > self.__d_paintedPoints ): doClip = not self.canvas().testAttribute( Qt.WA_PaintOnScreen ) if ( doClip ): # Depending on the platform setting a clip might be an important # performance issue. F.e. for Qt Embedded this reduces the # part of the backing store that has to be copied out - maybe # to an unaccelerated frame buffer device. xMap = self.canvasMap( self.__d_curve.xAxis() ) yMap = self.canvasMap( self.__d_curve.yAxis() ) br = Qwt.qwtBoundingRect( curveData, self.__d_paintedPoints - 1, numPoints - 1 ) clipRect = Qwt.QwtScaleMap.transform( xMap, yMap, br ).toRect() self.__d_directPainter.setClipRegion( QRegion(clipRect) ) self.__d_directPainter.drawSeries( self.__d_curve, self.__d_paintedPoints - 1, numPoints - 1 ) self.__d_paintedPoints = numPoints curveData.values().unlock()
def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
def resizeEvent(self, event): side = min(self.width(), self.height()) maskedRegion = QRegion(self.width() / 2 - side / 2, self.height() / 2 - side / 2, side, side, QRegion.Ellipse) self.setMask(maskedRegion)
def setTileRegion(self, region): if type(region) != QRegion: region = QRegion(region) if (self.mRegion == region): return self.mRegion = region self.updateBoundingRect()
def __init__(self): super().__init__() self.mMapDocument = None self.mBoundingRect = QRectF() self.mRegion = QRegion() self.setFlag(QGraphicsItem.ItemUsesExtendedStyleOption)
def resizeEvent(self, event): if self.orientation() == Qt.Horizontal: self.setContentsMargins(2, 0, 2, 0) else: self.setContentsMargins(0, 2, 0, 2) self.setMask(QRegion(self.contentsRect())) super().resizeEvent(event)
def mouseMoveEvent(self, a0: QMouseEvent) -> None: if (a0.buttons() == Qt.LeftButton) and abs(a0.pos().y()) > 30: globalPos = self.mapToGlobal(a0.pos()) posInTab = self.mapFromGlobal(globalPos) TabBar.indexTabToDrag = self.currentIndex() tabRect = self.tabRect(self.indexTabToDrag) pixmap = QPixmap(tabRect.size()) self.render(pixmap, QPoint(), QRegion(tabRect)) mimeData = QMimeData() drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) cursor = QCursor(Qt.OpenHandCursor) drag.setHotSpot(cursor.pos()) drag.setHotSpot(a0.pos() - posInTab) drag.setDragCursor(cursor.pixmap(), Qt.MoveAction) dropAction = drag.exec(Qt.MoveAction) # If the drag completed outside of the tab bar, detach the tab and move # the content to the current cursor position if dropAction == Qt.IgnoreAction: a0.accept() self.detachTab(self.indexTabToDrag, self.cursor().pos()) else: super(TabBar, self).mouseMoveEvent(a0)
def __init__(self, parent=None): super().__init__(self.tr("Bucket Fill Tool"), QIcon(":images/22x22/stock-tool-bucket-fill.png"), QKeySequence(self.tr("F")), parent) self.mStamp = TileStamp() self.mFillOverlay = None self.mFillRegion = QRegion() self.mMissingTilesets = QVector() self.mIsActive = False self.mLastShiftStatus = False ## # Indicates if the tool is using the random mode. ## self.mIsRandom = False ## # Contains the value of mIsRandom at that time, when the latest call of # tilePositionChanged() took place. # This variable is needed to detect if the random mode was changed during # mFillOverlay being brushed at an area. ## self.mLastRandomStatus = False ## # Contains all used random cells to use in random mode. # The same cell can be in the list multiple times to make different # random weights possible. ## self.mRandomCellPicker = RandomPicker()
def mousePressed(self, event): if (event.button() != Qt.LeftButton or self.mFillRegion.isEmpty()): return if (not self.brushItem().isVisible()): return preview = self.mFillOverlay if not preview: return paint = PaintTileLayer(self.mapDocument(), self.currentTileLayer(), preview.x(), preview.y(), preview) paint.setText(QCoreApplication.translate("Undo Commands", "Fill Area")) if not self.mMissingTilesets.isEmpty(): for tileset in self.mMissingTilesets: AddTileset(self.mapDocument(), tileset, paint) self.mMissingTilesets.clear() fillRegion = QRegion(self.mFillRegion) self.mapDocument().undoStack().push(paint) self.mapDocument().emitRegionEdited(fillRegion, self.currentTileLayer())
def renderToPixmap( widget: QWidget, outputPath=None ): rectangle = widget.geometry() pixmap = QPixmap( rectangle.size() ) widget.render( pixmap, QPoint(), QRegion(rectangle) ) if outputPath is not None: pixmap.save( outputPath ) return pixmap
def enableMask(self, enable): if not enable or Colors.noWindowMask: self.clearMask() else: region = QPolygon([ # North side. 0, 0, 800, 0, # East side. # 800, 70, # 790, 90, # 790, 480, # 800, 500, 800, 600, # South side. 700, 600, 670, 590, 130, 590, 100, 600, 0, 600, # West side. # 0, 550, # 10, 530, # 10, 520, # 0, 520, 0, 0]) self.setMask(QRegion(region))
def selectNone(self): if (not self.mMapDocument): return if (self.mMapDocument.selectedArea().isEmpty()): return command = ChangeSelectedArea(self.mMapDocument, QRegion()) self.mMapDocument.undoStack().push(command)
def __init__(self, parent=None, **kwargs): QWidget.__init__(self, parent, **kwargs) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.__tabs = [] self.__currentIndex = -1 self.__changeOnHover = False self.__iconSize = QSize(26, 26) self.__group = QButtonGroup(self, exclusive=True) self.__group.buttonPressed[QAbstractButton].connect( self.__onButtonPressed ) self.setMouseTracking(True) self.__sloppyButton = None self.__sloppyRegion = QRegion() self.__sloppyTimer = QTimer(self, singleShot=True) self.__sloppyTimer.timeout.connect(self.__onSloppyTimeout)
def highlight(self, highlighter, areas, msec=0): """Highlights the list of areas using the given highlighter. Every area is a two-tuple (page, rect), where rect is a rectangle inside (0, 0, 1, 1) like the linkArea attribute of a Poppler.Link. """ d = collections.defaultdict(list) for page, area in areas: d[page].append(area) d = weakref.WeakKeyDictionary(d) if msec: def clear(selfref=weakref.ref(self)): self = selfref() if self: self.clearHighlight(highlighter) t = QTimer(singleShot=True, timeout=clear) t.start(msec) else: t = None self.clearHighlight(highlighter) self._highlights[highlighter] = (d, t) self.update(sum((page.rect() for page in d), QRegion()))
def take_screenshot(window, screenshots_dir): timestamp = int(time.time()) pixmap = QPixmap(window.rect().size()) window.render(pixmap, QPoint(), QRegion(window.rect())) screenshots_dir.mkdir(exist_ok=True) img_name = 'exception_screenshot_%d.jpg' % timestamp pixmap.save(str(screenshots_dir / img_name))
def clip(self, p, w, h): """Clip image before painting Parameters ---------- p : QPainter object used for painting w : image width h : image height Returns ------- """ if self.clip_rect is not None: if isinstance(self.clip_rect[0], tuple): points = [ QPoint(int(w * x), int(h * y)) for (x, y) in self.clip_rect ] p.setClipRegion(QRegion(QPolygon(points))) else: p.setClipRect( self.clip_rect[0] * w, self.clip_rect[1] * h, self.clip_rect[2] * w, self.clip_rect[3] * h, )