def __init__(self, root_node, parent=None): super(AddDeviceDlg, self).__init__(parent) self.setWindowTitle("Add Relief Device") id_label = QLabel("&Relief Device ID:") self.id_lineedit = QLineEdit() self.id_lineedit.setMaxLength(200) id_label.setBuddy(self.id_lineedit) area_label = QLabel("Associated Relief Device &Area:") self.area_combobox = QComboBox() for area in root_node.children: self.area_combobox.addItem(area.name, area) area_label.setBuddy(self.area_combobox) color_label = QLabel("&Text Color:") self.color_combobox = QComboBox() for key in sorted(COLORS.keys()): pixmap = QPixmap(26, 26) pixmap.fill(COLORS[key]) self.color_combobox.addItem(QIcon(pixmap), key) color_label.setBuddy(self.color_combobox) button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) layout = QGridLayout() layout.addWidget(id_label, 0, 0) layout.addWidget(self.id_lineedit, 0, 1) layout.addWidget(area_label, 1, 0) layout.addWidget(self.area_combobox, 1, 1) layout.addWidget(color_label, 2, 0) layout.addWidget(self.color_combobox, 2, 1) layout.addWidget(button_box, 3, 1) self.setLayout(layout) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject)
def drawIconWithShadow(icon, rect, p, iconMode, radius, color, offset): cache = QPixmap() pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height()) if not QPixmapCache.find(pixmapName, cache): px = icon.pixmap(rect.size()) cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cachePainter = QPainter(cache) if iconMode == QIcon.Disabled: im = px.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(im.height()): scanLine = im.scanLine(y) for x in range(im.width()): pixel = scanLine intensity = qGray(pixel) scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanLine += 1 px = QPixmap.fromImage(im) # Draw shadow tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmpPainter = QPainter(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_Source) tmpPainter.drawPixmap(QPoint(radius, radius), px) tmpPainter.end() # blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blurred.fill(Qt.transparent) blurPainter = QPainter(blurred) # todo : blur image blurPainter.end() tmp = blurred # blacken the image tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() # draw the blurred drop shadow... cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap... cachePainter.drawPixmap(QPoint(radius, radius) + offset, px) QPixmapCache.insert(pixmapName, cache) targetRect = cache.rect() targetRect.moveCenter(rect.center()) p.drawPixmap(targetRect.topLeft() - offset, cache)
def _update_cursor(self): x = self.diameter w, h = x, x pixmap = QPixmap(w, h) pixmap.fill(Qt.transparent) p = QPainter(pixmap) p.drawPoints(self._points) p.end() self._cursor_pixmap = pixmap.createMaskFromColor(Qt.transparent)
def size_changed(self, value): "Handle the slider drag event." size = self.ui.brush_demo_label.size() pixmap = QPixmap(100, 100) pixmap.fill(Qt.white) cx, cy = int(size.width() / 2), int(size.height() / 2) self.current_brush.set_size(value) self.current_brush.draw_marker(cx, cy, pixmap, 1) self.ui.brush_demo_label.setPixmap(pixmap)
def size_changed(self, value): "Handle the slider drag event." size = self.ui.brush_demo_label.size() pixmap = QPixmap(100, 100) pixmap.fill(Qt.white) cx, cy = int(size.width()/2), int(size.height()/2) self.current_brush.set_size(value) self.current_brush.draw_marker(cx, cy, pixmap, 1) self.ui.brush_demo_label.setPixmap(pixmap)
def x_bitmap_opaque ( self, bitmap ): """ Returns a version of the specified bitmap with no transparency. """ dx = bitmap.width() dy = bitmap.height() opaque_bitmap = QPixmap( dx, dy ) opaque_bitmap.fill( WindowColor ) q = QPainter( opaque_bitmap ) q.drawPixmap( 0, 0, bitmap ) return opaque_bitmap
def choose_color(): color = QColorDialog().getColor() msgbox = QMessageBox() if color.isValid(): pixmap = QPixmap(50, 50) pixmap.fill(color) msgbox.setWindowTitle(u'Selected Color') msgbox.setIconPixmap(pixmap) else: msgbox.setWindowTitle(u'No Color was Selected') msgbox.exec_()
def __init__(self, dock): """Construct a DragDockLabel for the given dock.""" super(DragDockLabel, self).__init__("Drag Me") self.dock = dock self.setAcceptDrops(True) self.setScaledContents(True) self.setAlignment(Qt.AlignHCenter | Qt.AlignTop) self.setToolTip("Click and drag to change parent.") pm = QPixmap(1, 10) pm.fill(Qt.black) self.setPixmap(pm)
def choose_color(): # Select color color = QColorDialog().getColor() # Report about result of selection in QMessageBox dialog msgbox = QMessageBox() if color.isValid(): # Create a memory image 50x50 filled with selected color to display # as a icon in the msgbox dialog pixmap = QPixmap(50, 50) pixmap.fill(color) msgbox.setWindowTitle(u'Selected Color') msgbox.setIconPixmap(pixmap) else: msgbox.setWindowTitle(u'No Color was Selected') msgbox.exec_()
def paint(self, painter, option, widget=None): """@reimp @public virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) """ #Q_UNUSED(option) #Q_UNUSED(widget) d = self.__d key = d.hash pm = QPixmap() if not QPixmapCache.find(key, pm): # Set up a convenient path path = QPainterPath() path.setFillRule(Qt.OddEvenFill) path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius), d.actualOuterRadius, d.actualOuterRadius) path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius), d.actualInnerRadius, d.actualInnerRadius) nActualDiameter = 2.0 * d.actualOuterRadius pm = QPixmap(nActualDiameter, nActualDiameter) pm.fill(Qt.transparent) p = QPainter(pm) # Draw the ring background p.setPen(Qt.NoPen) p.setBrush(d.backgroundColor) p.setRenderHint(QPainter.Antialiasing) p.drawPath(path) # Draw the ring foreground # TODO: Expose this gradient as Qml Property gradient = QConicalGradient(d.actualOuterRadius, d.actualOuterRadius, 0.0) gradient.setColorAt(0.0, Qt.transparent) gradient.setColorAt(0.05, d.foregroundColor) gradient.setColorAt(0.8, Qt.transparent) p.setBrush(gradient) p.drawPath(path) p.end() QPixmapCache.insert(key, pm) # Draw pixmap at center of item w, h = self.width(), self.height() sz = min(w, h) painter.drawPixmap(0.5 * (w - sz), 0.5 * (h - sz), pm)
def generateCursor(self, element): cursorPixmap = QPixmap(32,32) hotX = element.getAttribute('__hotX') if hotX == None: hotX = element.width()/2 hotY = element.getAttribute('__hotY') if hotY == None: hotY = element.height()/2 cursorPixmap.fill(Qt.transparent) element.moveTo(0,0) painter = QPainter() painter.begin(cursorPixmap) id = element.getAttribute('id') assert id != None and isinstance(id,str) self.render(painter,"#" + id) painter.end() return QCursor(cursorPixmap,hotX,hotY)
def createColors(self): for style in MOAIDebugDrawStyles: colorBtn = getattr(self.ui, style + "Color") colorBtn.color = QColor(255, 255, 255, 255) pixmap = QPixmap(16, 16) pixmap.fill(colorBtn.color) colorBtn.pixmap = pixmap colorBtn.setIcon(pixmap) colorBtn.setAutoFillBackground(False) colorBtn.setIconSize(QtCore.QSize(16, 16)) def setColor(self, color): self.pixmap.fill(color) self.setIcon(self.pixmap) self.color = color colorBtn.setColor = types.MethodType(setColor, colorBtn)
def update_cursor(self, shape, size): self.cursor_size = size self.shape = shape cursor_pix = QPixmap(size, size) cursor_pix.fill(Qt.transparent) painter = QPainter(cursor_pix) painter.setPen(QColor(255, 0, 0)) if shape == 'circle': painter.drawEllipse(0, 0, size - 1, size - 1) elif shape == 'square': painter.drawRect(0, 0, size - 1, size - 1) elif shape == "magic wand": magic_wand.render(painter, QRect(0, 0, 20, 20)) cursor = QCursor(cursor_pix, 0, 0) self.setCursor(cursor) del painter
class QPixmapQDatastream(UsesQApplication): '''QDataStream <<>> QPixmap''' def setUp(self): super(QPixmapQDatastream, self).setUp() self.source_pixmap = QPixmap(100, 100) self.source_pixmap.fill(Qt.red) self.output_pixmap = QPixmap() self.buffer = QByteArray() self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly) self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly) def testStream(self): self.write_stream << self.source_pixmap self.read_stream >> self.output_pixmap image = self.output_pixmap.toImage() pixel = image.pixel(10, 10) self.assertEqual(pixel, QColor(Qt.red).rgba()) self.assertEqual(self.source_pixmap.toImage(), self.output_pixmap.toImage())
class QPixmapQDatastream(UsesQApplication): '''QDataStream <<>> QPixmap''' def setUp(self): super(QPixmapQDatastream, self).setUp() self.source_pixmap = QPixmap(100, 100) self.source_pixmap.fill(Qt.red) self.output_pixmap = QPixmap() self.buffer = QByteArray() self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly) self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly) def testStream(self): self.write_stream << self.source_pixmap self.read_stream >> self.output_pixmap image = self.output_pixmap.toImage() pixel = image.pixel(10,10) self.assertEqual(pixel, QColor(Qt.red).rgba()) self.assertEqual(self.source_pixmap.toImage(), self.output_pixmap.toImage())
def addLayer(self, name, visible, frozen, zValue, color, lineType, lineWeight, print_): """ TOWRITE for :class:`LayerManager`. :param `name`: TOWRITE :type `name`: QString :param `visible`: TOWRITE :type `visible`: bool :param `frozen`: TOWRITE :type `frozen`: bool :param `zValue`: TOWRITE :type `zValue`: qreal :param `color`: TOWRITE :type `color`: QRgb :param `lineType`: TOWRITE :type `lineType`: QString :param `lineWeight`: TOWRITE :type `lineWeight`: QString :param `print_`: TOWRITE :type `print_`: bool """ self.layerModel.insertRow(0) self.layerModel.setData(self.layerModel.index(0, 0), name) self.layerModel.setData(self.layerModel.index(0, 1), visible) self.layerModel.setData(self.layerModel.index(0, 2), frozen) self.layerModel.setData(self.layerModel.index(0, 3), zValue) colorPix = QPixmap(QSize(16, 16)) colorPix.fill(QColor(color)) self.layerModel.itemFromIndex(self.layerModel.index(0, 4)).setIcon( QIcon(colorPix)) self.layerModel.setData(self.layerModel.index(0, 4), QColor(color)) self.layerModel.setData(self.layerModel.index(0, 5), lineType) self.layerModel.setData(self.layerModel.index(0, 6), lineWeight) self.layerModel.setData(self.layerModel.index(0, 7), print_)
def paintEvent(self, event): painter = QStylePainter(self) painter.setPen(self.palette().color(QPalette.Text)) # Draw the combobox frame, focus rect, selected etc. opt = QStyleOptionComboBox() self.initStyleOption(opt) opt.currentText = "" # Don't draw the raw HTML painter.drawComplexControl(QStyle.CC_ComboBox, opt) # Draw the icon and text painter.drawControl(QStyle.CE_ComboBoxLabel, opt) # Draw the HTML self.label.setText(self.currentText()) self.label.adjustSize() pixmap = QPixmap(self.label.width(), self.label.height()) pixmap.fill(Qt.transparent) self.label.render(pixmap, renderFlags=QWidget.RenderFlags(0)) rect = QRect(opt.rect) y = (rect.height() - self.label.height()) / 2 rect.setX(self.fontMetrics().width("n")) rect.setY(y) rect.setHeight(pixmap.height()) rect.setWidth(pixmap.width()) painter.drawPixmap(rect, pixmap, pixmap.rect())
def addLayer(self, name, visible, frozen, zValue, color, lineType, lineWeight, print_): """ TOWRITE for :class:`LayerManager`. :param `name`: TOWRITE :type `name`: QString :param `visible`: TOWRITE :type `visible`: bool :param `frozen`: TOWRITE :type `frozen`: bool :param `zValue`: TOWRITE :type `zValue`: qreal :param `color`: TOWRITE :type `color`: QRgb :param `lineType`: TOWRITE :type `lineType`: QString :param `lineWeight`: TOWRITE :type `lineWeight`: QString :param `print_`: TOWRITE :type `print_`: bool """ self.layerModel.insertRow(0) self.layerModel.setData(self.layerModel.index(0, 0), name) self.layerModel.setData(self.layerModel.index(0, 1), visible) self.layerModel.setData(self.layerModel.index(0, 2), frozen) self.layerModel.setData(self.layerModel.index(0, 3), zValue) colorPix = QPixmap(QSize(16, 16)) colorPix.fill(QColor(color)) self.layerModel.itemFromIndex(self.layerModel.index(0, 4)).setIcon(QIcon(colorPix)) self.layerModel.setData(self.layerModel.index(0, 4), QColor(color)) self.layerModel.setData(self.layerModel.index(0, 5), lineType) self.layerModel.setData(self.layerModel.index(0, 6), lineWeight) self.layerModel.setData(self.layerModel.index(0, 7), print_)
class MainWindow(QMainWindow): """docstring for MainWindow""" def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.serviceProvider = 0 self.popupMenu = None self.mapControlButtons = [] self.mapControlTypes = [] self.markerObjects = [] self.setWindowTitle(self.tr('Map Viewer Demo')) self.routingManager = None self.mapManager = None self.mapWidget = None self.markerIcon = None self.slider = None manager = QNetworkConfigurationManager() canStartIAP = manager.capabilities() & QNetworkConfigurationManager.CanStartAndStopInterfaces configuration = manager.defaultConfiguration() if not configuration.isValid or (not canStartIAP and configuration.starte() != QNetworkConfiguration.Active): QMessageBox.information(self, self.tr('Map Viewer Demo'), self.tr('Available Access Points not found.')) return self.session = QNetworkSession(configuration, self) self.session.opened.connect(self.networkSessionOpened) self.session.error.connect(self.error) self.session.open() self.session.waitForOpened() self.setProvider('nokia') self.setupUi() def networkSessionOpened(self): pass def sliderValueChanged(self, value): self.mapWidget.setZoomLevel(value) def mapZoomLevelChanged(self, level): self.slider.setSliderPosition(int(level)) def mapTypeChanged(self, newType): index = self.mapControlTypes.index(newType) if index != -1: self.mapControButtons[index].setChecked(True) def mapTypeToggled(self, checked): if checked: button = self.sender() index = self.mapControlButtons.index(button) if index != -1: print index, self.mapControlTypes[index] self.mapWidget.setMapType(self.mapControlTypes[index]) def updateCoords(self, coords): if not coords.isValid(): return self.latitudeEdit.setText('%f' % coords.latitude()) self.longitudeEdit.setText('%f' % coords.longitude()) def setCoordsClicked(self): lat = float(self.latitudeEdit.text()) lon = float(self.longitudeEdit.text()) self.mapWidget.setCenter(QGeoCoordinate(lat, lon)) def setProvider(self, providerId): self.serviceProvider = QGeoServiceProvider(providerId) if self.serviceProvider.error() != QGeoServiceProvider.NoError: QMessageBox.information(self, self.tr('MapViewer Example'), self.tr('Unable to dinf the %s geoservices plugin.' % providerId)) qApp.quit() return self.mapManager = self.serviceProvider.mappingManager() self.routingManager = self.serviceProvider.routingManager() def error(self, error): if error == QNetworkSession.UnknownSessionError: msgBox = QMessageBox(self.parent()) msgBox.setText('This application requires network access to function.') msgBox.setInformativeText('Press Cancel to quit the application.') msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel) msgBox.setIcon(QMessageBox.Information) msgBox.setDefaultButton(QMessageBox.Retry) ret = msgBox.exec_() if ret == QMessageBox.Retry: QTimer.singleShot(0, self.session.open) elif ret == QMessageBox.Cancel: self.close() elif error == QNetworkSession.SessionAbortedError: msgBox = QMessageBox(self.parent()) msgBox.setText('Out of range of network') msgBox.setInformativeText('Move back into range and press Retry, or press Cancel to quit the application') msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel) msgBox.setIcon(QMessageBox.Information) msgBox.setDefaultButton(QMessageBox.Retry) ret = msgBox.exec_() if ret == QMessageBox.Retry: QTimer.singleShot(0, self.session.open) elif ret == QMessageBox.Cancel: self.close() def setupUi(self): scene = QGraphicsScene(self) self.view = QGraphicsView(scene, self) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVisible(True) self.view.setInteractive(True) self.createPixmapIcon() self.mapWidget = MapWidget(self.mapManager) scene.addItem(self.mapWidget) self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95)) self.mapWidget.setZoomLevel(5) #... self.slider = QSlider(Qt.Vertical, self) self.slider.setTickInterval(1) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setMaximum(self.mapManager.maximumZoomLevel()) self.slider.setMinimum(self.mapManager.minimumZoomLevel()) self.slider.valueChanged[int].connect(self.sliderValueChanged) self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged) mapControlLayout = QVBoxLayout() self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged) for mapType in self.mapWidget.supportedMapTypes(): radio = QRadioButton(self) if mapType == QGraphicsGeoMap.StreetMap: radio.setText('Street') elif mapType == QGraphicsGeoMap.SatelliteMapDay: radio.setText('Sattelite') elif mapType == QGraphicsGeoMap.SatelliteMapNight: radio.setText('Sattelite - Night') elif mapType == QGraphicsGeoMap.TerrainMap: radio.setText('Terrain') if mapType == self.mapWidget.mapType(): radio.setChecked(True) radio.toggled[bool].connect(self.mapTypeToggled) self.mapControlButtons.append(radio) self.mapControlTypes.append(mapType) mapControlLayout.addWidget(radio) self.latitudeEdit = QLineEdit() self.longitudeEdit = QLineEdit() formLayout = QFormLayout() formLayout.addRow('Latitude', self.latitudeEdit) formLayout.addRow('Longitude', self.longitudeEdit) self.captureCoordsButton = QToolButton() self.captureCoordsButton.setText('Capture coordinates') self.captureCoordsButton.setCheckable(True) self.captureCoordsButton.toggled[bool].connect( self.mapWidget.setMouseClickCoordQuery) self.mapWidget.coordQueryResult.connect(self.updateCoords) self.setCoordsButton = QPushButton() self.setCoordsButton.setText('Set coordinates') self.setCoordsButton.clicked.connect(self.setCoordsClicked) buttonLayout = QHBoxLayout() buttonLayout.addWidget(self.captureCoordsButton) buttonLayout.addWidget(self.setCoordsButton) coordControlLayout = QVBoxLayout() coordControlLayout.addLayout(formLayout) coordControlLayout.addLayout(buttonLayout) widget = QWidget(self) layout = QGridLayout() layout.setRowStretch(0, 1) layout.setRowStretch(1, 0) topLayout = QGridLayout() bottomLayout = QGridLayout() topLayout.setColumnStretch(0, 0) topLayout.setColumnStretch(1, 1) bottomLayout.setColumnStretch(0, 0) bottomLayout.setColumnStretch(1, 1) topLayout.addWidget(self.slider, 0, 0) topLayout.addWidget(self.view, 0, 1) bottomLayout.addLayout(mapControlLayout, 0, 0) bottomLayout.addLayout(coordControlLayout, 0, 1) layout.addLayout(topLayout, 0, 0) layout.addLayout(bottomLayout, 1, 0) self.layout = layout widget.setLayout(layout) self.setCentralWidget(widget) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.customContextMenuRequest) def createPixmapIcon(self): self.markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT) self.markerIcon.fill(Qt.transparent) painter = QPainter(self.markerIcon) p1 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1) p2 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN) pen = QPen(Qt.black) pen.setWidth(2) pen.setCosmetic(True) painter.setPen(pen) painter.drawLine(p1, p2) ellipse = QRect(0, 0, MARKER_WIDTH - 1, MARKER_HEIGHT - 1) pen.setWidth(1) painter.setPen(pen) color = QColor(Qt.green) color.setAlpha(127) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse(ellipse) def resizeEvent(self, event): self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size())) self.mapWidget.resize(self.view.size()) def showEvent(self, event): self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size())) self.mapWidget.resize(self.view.size()) def createMenus(self): self.popupMenu = QMenu(self) # Markers subMenuItem = QMenu(self.tr('Marker'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Set marker'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPixmap) menuItem = QAction(self.tr('Remove marker'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.removePixmaps) menuItem = QAction(self.tr('Select objects'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.selectObjects) # Draw subMenuItem = QMenu(self.tr('Draw'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Rectangle'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawRect) menuItem = QAction(self.tr('Polyline'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPolyline) menuItem = QAction(self.tr('Polygon'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPolygon) menuItem = QAction(self.tr('Circle'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawCircle) menuItem = QAction(self.tr('Text'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawText) # Routing subMenuItem = QMenu(self.tr('Route'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Calculate route'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.calculateRoute) def selectObjects(self): for obj in self.mapWidget.mapObjects(): obj.setSelected(False) if len(self.markerObjects) < 2: return bottomRight = self.markerObjects.pop() topLeft = self.markerObjects.pop() self.mapWidget.removeMapObject(topLeft) self.mapWidget.removeMapObject(bottomRight) selectedObjects = self.mapWidget.mapObjectsInScreenRect( QRectF(self.mapWidget.coordinateToScreenPosition(topLeft.coordinate()), self.mapWidget.coordinateToScreenPosition(bottomRight.coordinate())) ) for obj in selectedObjects: obj.setSelected(True) def drawRect(self): if len(self.markerObjects) < 2: return p1, p2 = self.markerObjects[:2] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) fill = QColor(Qt.black) fill.setAlpha(65) rectangle = QGeoMapRectangleObject(p1.coordinate(), p2.coordinate()) rectangle.setPen(pen) rectangle.setBrush(QBrush(fill)) self.mapWidget.addMapObject(rectangle) def drawPolyline(self): path = [mark.coordinate() for mark in self.markerObjects] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) polyline = QGeoMapPolylineObject() polyline.setPen(pen) polyline.setPath(path) self.mapWidget.addMapObject(polyline) def drawPolygon(self): path = [mark.coordinate() for mark in self.markerObjects] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) polygon = QGeoMapPolygonObject() polygon.setPen(pen) fill = QColor(Qt.black) fill.setAlpha(65) polygon.setBrush(QBrush(fill)) polygon.setPath(path) self.mapWidget.addMapObject(polygon) def drawCircle(self): if not len(self.markerObjects): return p1 = self.markerObjects[0] center = p1.coordinate() radius = 3000 # Meters if len(self.markerObjects) >= 2: radius = center.distanceTo(self.markerObjects[1].coordinate()) pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) circle = QGeoMapCircleObject(center, radius) circle.setPen(pen) fill = QColor(Qt.black) fill.setAlpha(65) circle.setBrush(QBrush(fill)) self.mapWidget.addMapObject(circle) def drawText(self): if not len(self.markerObjects): return start = self.markerObjects[0].coordinate() text = QGeoMapTextObject(start, 'Text') fill = QColor(Qt.black) text.setBrush(fill) self.mapWidget.addMapObject(text) def calculateRoute(self): if len(self.markerObjects) < 2: return waypoints = [x.coordinate() for x in self.markerObjects[:2]] request = QGeoRouteRequest(waypoints) self.routeReply = self.routingManager.calculateRoute(request) self.routeReply.finished.connect(self.routeFinished) def routeFinished(self): if not self.routeReply.routes(): return route = QGeoMapRouteObject(self.routeReply.routes()[0]) routeColor = QColor(Qt.blue) routeColor.setAlpha(127) pen = QPen(routeColor) pen.setWidth(7) pen.setCosmetic(True) pen.setCapStyle(Qt.RoundCap) route.setPen(pen) self.mapWidget.addMapObject(route) def drawPixmap(self): marker = QGeoMapPixmapObject(self.mapWidget.screenPositionToCoordinate(self.lastClicked), QPoint(-(MARKER_WIDTH / 2), -MARKER_HEIGHT), self.markerIcon) self.mapWidget.addMapObject(marker) self.markerObjects.append(marker) def removePixmaps(self): for i in range(len(self.markerObjects)): marker = self.markerObjects.pop() self.mapWidget.removeMapObject(marker) marker.deleteLater() def customContextMenuRequest(self, point): self.lastClicked = point if self.focusWidget() == self.view: if not self.popupMenu: self.createMenus() self.popupMenu.popup(self.view.mapToGlobal(self.lastClicked))
def drag ( self, data, type = None, request = 'copy', image = None ): """ Initiates a drag operation with the specified *data*. If *type* is **None**, the control will try to determine the kind of data being dragged from the data itself. Other than **None**, the legal values for *type* are: 'color', 'image', 'text', 'html', 'files', 'urls' and 'object'. *Request* specifies whether the data is to be copied ('copy'), moved ('move') or linked ('link'), with the default request being to copy the data. *Image* specifies an ImageResource image to be used while dragging to provide the user with some indication of what is being dragged. This may not be supported with all UI back-ends. If not supported, the *image* value is treated as *None*. A value of *None* indicates that the default drag image should be used. The result is a string indicating the action taken by the receiver (if any) of the data at the completion of the drag and drop operation. The possible values are: 'copy', 'move', 'link' and 'ignore'. """ if type is None: if isinstance( data, basestring ): type = 'text' elif isinstance( data, QColor ): type = 'color' elif isinstance( data, AnImageResource ): type = 'image' data = data.image elif isinstance( data, SequenceTypes ): type = 'urls' data = [ QUrl( item ) for item in data ] else: type = 'object' mime_data = getattr( self, '_drag_%s' % type, self._drag_object )( data ) drag = QDrag( self.control ) drag.setMimeData( mime_data ) # Set up the drag image (if one was specified): if isinstance( image, AnImageResource ): bitmap = image.bitmap idx, idy = image.width, image.height ratio = max( idx, idy ) / 128.0 if ratio > 1.0: # Create a scaled version of the image if it is larger than the # maximum nominal size: sdx = int( round( idx / ratio ) ) sdy = int( round( idy / ratio ) ) pm = QPixmap( sdx, sdy ) pm.fill( QColor( 0, 0, 0, 0 ) ) painter = painter_for( pm ) painter.drawPixmap( 0, 0, sdx, sdy, bitmap, 0, 0, idx, idy ) painter.end() bitmap, idx, idy = pm, sdx, sdy drag.setPixmap( bitmap ) drag.setHotSpot( QPoint( idx / 2, idy / 2 ) ) return RequestAction[ drag.exec_() ]
def _set_icon(self, color): """Set the colored square icon.""" colorpix = QPixmap(16, 16) colorpix.fill(color) self.setIcon(QIcon(colorpix))
from PySide.QtGui import (QApplication, QGraphicsView, QGraphicsScene, QMainWindow, QPixmap, QPainter) from PySide.QtCore import Qt import sys if __name__ == '__main__': app = QApplication(sys.argv) scene = QGraphicsScene() view = QGraphicsView(scene) view.scale(15, 15) pix = QPixmap(200, 50) pix.fill(Qt.white) p = QPainter(pix) p.setPen(Qt.black) #p.setBrush(Qt.red) for i in range(1, 10): p.drawEllipse(0, 0, i, i) p.translate(i+5, 0) p.end() pixItem = scene.addPixmap(pix) win = QMainWindow() win.setCentralWidget(view) win.resize(700, 200) win.show() sys.exit(app.exec_())
class Fourier(QWidget): """ Actual fourier display and drawing widget """ fourier_updated = Signal(np.ndarray) image = None pressed = False scale_factor = None color = QColor(0, 0, 0) raw_fourier = None x_sym = False y_sym = False opp_sym = False # signal fourier updated def __init__(self, parent=None): super().__init__(parent) self.update_cursor('square', 20) self.overlay = Overlay(self) def update_image(self, fft_array, factor=None): scaled_values, sf = rescale_array(np.real(np.log2(fft_array)), self.scale_factor) self.scale_factor = sf self.image = array_to_image(scaled_values) self.setMinimumSize(self.image.size()) self.overlay.resize(self.image.size()) self.update() self.updateGeometry() # I have to deliver, and it's broken on windows. self.setMinimumSize(self.image.size()) self.overlay.resize(self.image.size()) self.update() self.updateGeometry() def update_fourier(self, image_array, flush=False): f = array_to_fft(image_array) if self.raw_fourier is None or flush: self.original = f.copy() self.raw_fourier = f.copy() self.update_image(self.raw_fourier) def update_cursor(self, shape, size): self.cursor_size = size self.shape = shape cursor_pix = QPixmap(size, size) cursor_pix.fill(Qt.transparent) painter = QPainter(cursor_pix) painter.setPen(QColor(255, 0, 0)) if shape == 'circle': painter.drawEllipse(0, 0, size - 1, size - 1) elif shape == 'square': painter.drawRect(0, 0, size - 1, size - 1) elif shape == "magic wand": magic_wand.render(painter, QRect(0, 0, 20, 20)) cursor = QCursor(cursor_pix, 0, 0) self.setCursor(cursor) del painter def on_size_change(self, size): """ Brush size changed """ self.cursor_size = size self.update_cursor(self.shape, self.cursor_size) Slot(str) def on_shape_change(self, shape): """ Brush shape changed """ self.shape = shape self.update_cursor(self.shape, self.cursor_size) def on_color_change(self, color): self.color = QColor(color, color, color) def emit_fourier(self): array = fft_to_array(self.raw_fourier) self.fourier_updated.emit(array) def on_restore(self): self.raw_fourier = self.original.copy() self.update_image(self.raw_fourier, self.scale_factor) #self.fourier_updated.emit(self.raw_fourier.copy()) self.emit_fourier() def on_resize(self, factor): if factor == 1.0: return #even = lambda x: x if (x % 2 == 0) else x + 1 array = self.raw_fourier reshape = lambda x_y: [int(factor * x_y[0]), int(factor * x_y[1])] diff = lambda x_y: [x_y[0] - array.shape[0], x_y[1] - array.shape[1]] nexteven = lambda x: x if (x % 2 == 0) else x + 1 delta = map(nexteven, diff(reshape(array.shape))) newsize = tuple(x[0] + x[1] for x in zip(array.shape, delta)) self.raw_fourier = zeropad(array, newsize) self.update_image(self.raw_fourier, self.scale_factor) #self.fourier_updated.emit(self.raw_fourier.copy()) self.emit_fourier() def draw_mask_on_fourier(self, mask, value=0x00): self.raw_fourier[mask] = 2**value self.update_image(self.raw_fourier, self.scale_factor) self.emit_fourier() def regen_image(self): self.update_image(self.raw_fourier, self.scale_factor) def paintEvent(self, event): """ Paint widget as self.image content """ if self.image is None: super().paintEvent(event) return painter = QPainter(self) rect = event.rect() painter.drawImage(rect.topLeft(), self.image, rect) def mousePressEvent(self, event): self.pressed = True self.draw_buffer = QPixmap(self.image.size()) color = self.color.red() ^ 0xAA self.draw_buffer.fill(QColor(color, color, color)) self.draw(event) def mouseReleaseEvent(self, event): self.pressed = False self.draw(event) self.fourier_draw() def mouseMoveEvent(self, event): if self.pressed: self.draw(event) def fourier_draw(self): arr = image_to_array(self.draw_buffer.toImage()) values = arr[arr == self.color.red()] * (self.scale_factor / 255) self.raw_fourier[arr == self.color.red()] = np.abs(2**values) self.emit_fourier() def _paint(self, painter, x, y): size = self.cursor_size shape = self.shape painter.setBrush(self.color) painter.setPen(Qt.NoPen) if shape == 'circle': painter.drawEllipse(x, y, size - 1, size - 1) elif shape == 'square': painter.drawRect(x, y, size - 1, size - 1) elif shape == "magic wand": magic_wand.render(painter, QRect(0, 0, 20, 20)) def draw(self, event): x, y = event.x(), event.y() max_y, max_x = self.raw_fourier.shape for painter in map(QPainter, [self.image, self.draw_buffer]): self._paint(painter, x, y) if self.x_sym: self._paint(painter, abs(max_x - x - self.cursor_size), y) if self.y_sym: self._paint(painter, x, abs(max_y - y - self.cursor_size)) if (self.x_sym and self.y_sym) or self.opp_sym: self._paint(painter, abs(max_x - x - self.cursor_size), abs(max_y - y - self.cursor_size)) del painter self.update() def sizeHint(self): if not self.image: return super().minimumSizeHint() return self.image.size() def on_y_toggle(self, y_state): self.y_sym = y_state def on_x_toggle(self, x_state): self.x_sym = x_state def on_opp_toggle(self, opp_state): self.opp_sym = opp_state