def store_data(self, id, data): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def __init__(self, parent=None, filename=None): super(MainForm, self).__init__(parent) self.view = GraphicsView() background = QPixmap(filename) self.filename = os.path.splitext(filename)[0] if ("-%s" % ORG) in self.filename: self.filename = self.filename[:-len(ORG)-5] + ".png" self.view.setBackgroundBrush(QBrush(background)) # self.view.setCacheMode(QGraphicsView.CacheBackground) # self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.scene = QGraphicsScene(self) global scene scene = self.scene self.view.dialog = self self.view.setScene(self.scene) self.prevPoint = QPoint() self.lastStamp = -1 buttonLayout = QVBoxLayout() for text, slot in ( ("&Tag", self.addTag), ("Align &bottom", self.alignBottom), ("Align &left", self.alignLeft), ("&Save", self.save), ("&Quit", self.accept)): button = QPushButton(text) if not MAC: button.setFocusPolicy(Qt.NoFocus) self.connect(button, SIGNAL("clicked()"), slot) if text == "&Save": buttonLayout.addStretch(5) if text == "&Quit": buttonLayout.addStretch(1) buttonLayout.addWidget(button) buttonLayout.addStretch() self.view.resize(background.width(), background.height()) self.scene.setSceneRect(0, 0, background.size().width(), background.size().height()) self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) layout = QHBoxLayout() layout.addWidget(self.view, 1) layout.addLayout(buttonLayout) self.setLayout(layout) self.setWindowTitle(AppName) info_name = self.filename + "-" + TAG + ".txt" if os.path.exists(info_name): for tag, x, y in [line.strip().split("\t") for line in open(info_name, "rt").readlines()]: self.addTag(int(tag), QPointF(int(x), int(y)), adjust_position=False) global Dirty; Dirty=False self.show() self.raise_()
class GraphicsPixmapWidget(QGraphicsWidget): """ A QGraphicsWidget displaying a QPixmap """ def __init__(self, pixmap=None, parent=None): super().__init__(parent) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) self._pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() self._keepAspect = True self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) def setPixmap(self, pixmap): self._pixmap = QPixmap(pixmap) self.updateGeometry() self.update() def pixmap(self): return QPixmap(self._pixmap) def setKeepAspectRatio(self, keep): if self._keepAspect != keep: self._keepAspect = bool(keep) self.update() def keepAspectRatio(self): return self._keepAspect def setGeometry(self, rect): self.prepareGeometryChange() super().setGeometry(rect) def sizeHint(self, which, constraint=QSizeF()): if which == Qt.PreferredSize: return QSizeF(self._pixmap.size()) else: return QGraphicsWidget.sizeHint(self, which, constraint) def paint(self, painter, option, widget=0): if self._pixmap.isNull(): return rect = self.contentsRect() pixsize = QSizeF(self._pixmap.size()) aspectmode = (Qt.KeepAspectRatio if self._keepAspect else Qt.IgnoreAspectRatio) pixsize.scale(rect.size(), aspectmode) pixrect = QRectF(QPointF(0, 0), pixsize) pixrect.moveCenter(rect.center()) painter.save() painter.setPen(QPen(QColor(0, 0, 0, 50), 3)) painter.drawRoundedRect(pixrect, 2, 2) painter.setRenderHint(QPainter.SmoothPixmapTransform) source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size())) painter.drawPixmap(pixrect, self._pixmap, source) painter.restore()
def resizeEvent(self, event): view_size = self.view.size() new_background_height = (1.5 / 4.) * view_size.height() background_to_pixmap = QPixmap(self.image_bank["Background to"]["path"]) background_to_pixmap = background_to_pixmap.scaled(new_background_height, new_background_height, Qt.KeepAspectRatio) if not self.background_to_image: self.background_to_image = QGraphicsPixmapItem(background_to_pixmap) else: self.background_to_image.setPixmap(background_to_pixmap) sugested_x_position = int(2 * (view_size.width() / 3.)) if sugested_x_position < 0: sugested_x_position = 0 sugested_y_position = int(view_size.height() / 2. - background_to_pixmap.size().height() / 2) if sugested_y_position < 0: sugested_y_position = 0 self.background_to_image.setPos(sugested_x_position, sugested_y_position) ##################### new_background_height = (2.2 / 4.) * view_size.height() background_from_pixmap = QPixmap(self.image_bank["Background from"]["path"]) background_from_pixmap = background_from_pixmap.scaled(new_background_height, new_background_height, Qt.KeepAspectRatio) if not self.background_to_image: self.background_from_image = QGraphicsPixmapItem(background_from_pixmap) else: self.background_from_image.setPixmap(background_from_pixmap) sugested_x_position = int(view_size.width() / 5. - background_from_pixmap.size().height() / 2) if sugested_x_position < 0: sugested_x_position = 0 sugested_y_position = int(view_size.height() / 2. - background_from_pixmap.size().height() / 2) if sugested_y_position < 0: sugested_y_position = 0 self.background_from_image.setPos(sugested_x_position, sugested_y_position) #### new_widget_height = (1 / 4.) * view_size.height() if self.image_bank is not None: for image_id in self.image_bank.keys(): if "clothes" in self.image_bank[image_id]["categories"]: widget = self.image_bank[image_id]["widget"] pixmap = widget.pixmap pixmap = pixmap.scaled(new_widget_height, new_widget_height, Qt.KeepAspectRatio) widget.setPixmap(pixmap) print widget.moved_flag if not widget.moved_flag: newpos_x = self.background_from_image.boundingRect().width() / 2 - widget.boundingRect().width() / 2 newpos_y = self.background_from_image.boundingRect().height() / 2 - widget.boundingRect().height() / 2 widget.setPos(newpos_x, newpos_y) super(TakeDragGame, self).resizeEvent(event)
def hotIcon(color): """ gets a hot area with its middle and its icon :param color: some color :type color: str :returns: the center and the pixmap of a hot area :rtype: tuple(QPoint, QPixmap) """ px=QPixmap(":/hot/hot-%s.svg" %color) middle=QPoint(px.size().width()/2, px.size().height()/2) return middle, px
class GraphicsPixmapWidget(QGraphicsWidget): def __init__(self, pixmap, parent=None): QGraphicsWidget.__init__(self, parent) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) self._pixmap = pixmap self._pixmapSize = QSizeF() self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) def setPixmap(self, pixmap): if self._pixmap != pixmap: self._pixmap = QPixmap(pixmap) self.updateGeometry() def pixmap(self): return QPixmap(self._pixmap) def setPixmapSize(self, size): if self._pixmapSize != size: self._pixmapSize = QSizeF(size) self.updateGeometry() def pixmapSize(self): if self._pixmapSize.isValid(): return QSizeF(self._pixmapSize) else: return QSizeF(self._pixmap.size()) def sizeHint(self, which, constraint=QSizeF()): if which == Qt.PreferredSize: return self.pixmapSize() else: return QGraphicsWidget.sizeHint(self, which, constraint) def paint(self, painter, option, widget=0): if self._pixmap.isNull(): return rect = self.contentsRect() pixsize = self.pixmapSize() pixrect = QRectF(QPointF(0, 0), pixsize) pixrect.moveCenter(rect.center()) painter.save() painter.setPen(QPen(QColor(0, 0, 0, 50), 3)) painter.drawRoundedRect(pixrect, 2, 2) painter.setRenderHint(QPainter.SmoothPixmapTransform) source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size())) painter.drawPixmap(pixrect, self._pixmap, source) painter.restore()
def __initializeUi(self): """ This method initializes the Widget ui. """ self.__clearButton.setCursor(Qt.ArrowCursor) if self.__uiClearImage and self.__uiClearClickedImage: pixmap = QPixmap(self.__uiClearImage) clickedPixmap = QPixmap(self.__uiClearClickedImage) self.__clearButton.setStyleSheet("QToolButton { border: none; padding: 0px; }") self.__clearButton.setIcon(QIcon(pixmap)) self.__clearButton.setMaximumSize(pixmap.size()) # Signals / Slots. self.__clearButton.pressed.connect(functools.partial(self.__clearButton.setIcon, QIcon(clickedPixmap))) self.__clearButton.released.connect(functools.partial(self.__clearButton.setIcon, QIcon(pixmap))) else: self.__clearButton.setText("Clear") frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) self.setStyleSheet(QString("QLineEdit {{ padding-left: {0}px; padding-right: {1}px; }}".format( self.__searchActiveLabel.sizeHint().width() + frameWidth, self.__clearButton.sizeHint().width() + frameWidth))) self.setMinimumSize(max(self.minimumSizeHint().width(), self.__clearButton.sizeHint().height() + frameWidth * 2), max(self.minimumSizeHint().height(), self.__clearButton.sizeHint().height() + frameWidth * 2)) self.__completer.setCaseSensitivity(Qt.CaseInsensitive) self.__completer.setCompletionMode(QCompleter.PopupCompletion)
def __initializeUi(self): """ Initializes the Widget ui. """ self.__clearButton.setCursor(Qt.ArrowCursor) if self.__uiClearImage and self.__uiClearClickedImage: pixmap = QPixmap(self.__uiClearImage) clickedPixmap = QPixmap(self.__uiClearClickedImage) self.__clearButton.setIcon(QIcon(pixmap)) self.__clearButton.setMaximumSize(pixmap.size()) # Signals / Slots. self.__clearButton.pressed.connect(functools.partial(self.__clearButton.setIcon, QIcon(clickedPixmap))) self.__clearButton.released.connect(functools.partial(self.__clearButton.setIcon, QIcon(pixmap))) else: self.__clearButton.setText("Clear") self.__setStyleSheet() frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) self.setMinimumSize( max(self.minimumSizeHint().width(), self.__clearButton.sizeHint().height() + frameWidth * 2), max(self.minimumSizeHint().height(), self.__clearButton.sizeHint().height() + frameWidth * 2), ) self.__completer.setCaseSensitivity(Qt.CaseInsensitive) self.__completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
def __initializeUi(self): """ Initializes the Widget ui. """ self.__clearButton.setCursor(Qt.ArrowCursor) if self.__uiClearImage and self.__uiClearClickedImage: pixmap = QPixmap(self.__uiClearImage) clickedPixmap = QPixmap(self.__uiClearClickedImage) self.__clearButton.setIcon(QIcon(pixmap)) self.__clearButton.setMaximumSize(pixmap.size()) # Signals / Slots. self.__clearButton.pressed.connect( functools.partial(self.__clearButton.setIcon, QIcon(clickedPixmap))) self.__clearButton.released.connect( functools.partial(self.__clearButton.setIcon, QIcon(pixmap))) else: self.__clearButton.setText("Clear") self.__setStyleSheet() frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) self.setMinimumSize( max(self.minimumSizeHint().width(), self.__clearButton.sizeHint().height() + frameWidth * 2), max(self.minimumSizeHint().height(), self.__clearButton.sizeHint().height() + frameWidth * 2)) self.__completer.setCaseSensitivity(Qt.CaseInsensitive) self.__completer.setCompletionMode( QCompleter.UnfilteredPopupCompletion)
def init_big_button(button, image_name): pix = QPixmap('/usr/share/ubiquity/qt/images/' + image_name) icon = QIcon(pix) button.setIcon(icon) button.setIconSize(pix.size()) # Set a fixed height to ensure the button text is not cropped # when the window is resized button.setFixedHeight(button.sizeHint().height())
def __init__(self, parent): QToolButton.__init__(self, parent) pixmap = QPixmap(":/search_clear_13") self.setIcon(QIcon(pixmap)) self.setIconSize(pixmap.size()) self.setCursor(Qt.ArrowCursor) self.setPopupMode(QToolButton.InstantPopup) stylesheet = "QToolButton { border: none; padding: 0px; }" self.setStyleSheet(stylesheet)
class GOBoard(QWidget): on_click = pyqtSignal(str, int) def __init__(self): super().__init__() self.__background_pixmap = QPixmap(get_asset_path("board.png")) self.__background_label = QLabel(self) self.__background_label.setPixmap(self.__background_pixmap) self.setMinimumSize(self.__background_pixmap.size()) self.__pieces = {} def pixmap_height(self): return self.__background_pixmap.height() def add_square(self, letter, y, color): y -= 1 letters = list(string.ascii_uppercase) letters.remove("I") a = letters.index(letter) if (letter, y + 1) in self.__pieces: print("ERROR: Space {},{} already occupied".format(letter, y + 1)) else: piece = GOSquare(27 + a * 23, self.__background_pixmap.height() - (20 + y * 23), color, self) self.__pieces[(letter, y + 1)] = piece piece.show() def add_piece(self, letter, y, text, color): y -= 1 letters = list(string.ascii_uppercase) letters.remove("I") a = letters.index(letter) if (letter, y + 1) in self.__pieces: print("ERROR: Space {},{} already occupied".format(letter, y + 1)) else: piece = GOPiece(23 + a * 23, self.__background_pixmap.height() - (24 + y * 23), text, color, self) self.__pieces[(letter, y + 1)] = piece piece.show() def remove_piece(self, letter, y): if (letter, y) in self.__pieces: piece = self.__pieces[(letter, y)] piece.hide() piece.deleteLater() del self.__pieces[(letter, y)] else: print("ERROR: There is no piece at {},{}".format(letter, y)) def mousePressEvent(self, e): x = (e.x() - 27) // 23 y = (self.__background_pixmap.height() - 20 - e.y()) // 23 y += 2 letters = list(string.ascii_uppercase) letters.remove("I") letra = letters[x] if y <= 19 and letra <= "T": self.on_click.emit(letra, y)
def __init__(self, parent): QToolButton.__init__(self, parent) pixmap = QPixmap(':/search_clear_13') self.setIcon(QIcon(pixmap)) self.setIconSize(pixmap.size()) self.setCursor(Qt.ArrowCursor) self.setPopupMode(QToolButton.InstantPopup) stylesheet = "QToolButton { border: none; padding: 0px; }" self.setStyleSheet(stylesheet)
def __init__(self, mess): super(errorMessage, self).__init__() msgBox = QMessageBox() msgBox.setWindowTitle("Erreur") msgBox.setText(mess) tmp = QPixmap(":/ourapp/warning") icon = QPixmap(tmp.scaled(QSize(32, 32))) print icon.size() msgBox.setIconPixmap(icon) msgBox.addButton( QPushButton('continue'), QMessageBox.NoRole) ret = msgBox.exec_() if ret == True: return
def _renderPixmaps(self): self._pixmaps=[] for i in range(self._steps+1): angle = int(i * 360.0 / self._steps) pixmap = QPixmap(self._resource) # if problem with loading png if pixmap.size().width()==0: self._pixmaps=None return rotate_matrix = QMatrix() rotate_matrix.rotate(angle) pixmap_rotated = pixmap.transformed(rotate_matrix) pixmap_moved = QPixmap(pixmap.size()) pixmap_moved.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap_moved) painter.drawPixmap((pixmap_moved.width() - pixmap_rotated.width()) / 2.0, (pixmap_moved.height() - pixmap_rotated.height()) / 2.0, pixmap_rotated) painter.end() self._pixmaps+=[pixmap_moved.scaled(self._width, self._height)]
def __init__( self, parent, canvasLayer ): QTreeWidgetItem.__init__( self ) self.legend = parent self.canvasLayer = canvasLayer self.canvasLayer.layer().setLayerName( self.legend.normalizeLayerName( unicode( self.canvasLayer.layer().name() ) ) ) self.setText( 0, self.canvasLayer.layer().name() ) self.isVect = ( self.canvasLayer.layer().type() == QgsMapLayer.VectorLayer ) # 0: Vector, 1: Raster #self.layerId = self.canvasLayer.layer().getLayerID() self.layerId = self.canvasLayer.layer().id() if self.isVect: geom = self.canvasLayer.layer().dataProvider().geometryType() self.setCheckState( 0, Qt.Checked ) pm = QPixmap( 20, 20 ) icon = QIcon() if self.isVect: if geom == QGis.WKBPoint or geom == QGis.WKBMultiPoint or geom == QGis.WKBPoint25D or geom == QGis.WKBMultiPoint25D: # Point icon.addPixmap( QPixmap( ":/icons/mIconPointLayer.png" ), QIcon.Normal, QIcon.On) elif geom == QGis.WKBLineString or geom == QGis.WKBMultiLineString or geom == QGis.WKBLineString25D or geom == QGis.WKBMultiLineString25D: # Polyline icon.addPixmap( QPixmap( ":/icons/mIconLineLayer.png"), QIcon.Normal, QIcon.On) elif geom == QGis.WKBPolygon or geom == QGis.WKBMultiPolygon or geom == QGis.WKBPolygon25D or geom == QGis.WKBMultiPolygon25D: # Polygon icon.addPixmap( QPixmap( ":/icons/mIconPolygonLayer.png"), QIcon.Normal, QIcon.On) else: # Not a valid WKT Geometry geom = self.canvasLayer.layer().geometryType() # QGis Geometry if geom == QGis.Point: # Point icon.addPixmap( QPixmap( ":/icons/mIconPointLayer.png" ), QIcon.Normal, QIcon.On) elif geom == QGis.Line: # Line icon.addPixmap( QPixmap( ":/icons/mIconLineLayer.png"), QIcon.Normal, QIcon.On) elif geom == QGis.Polygon: # Polygon icon.addPixmap( QPixmap( ":/icons/mIconPolygonLayer.png"), QIcon.Normal, QIcon.On) else: raise RuntimeError, 'Unknown geometry: ' + str( geom ) else: pm = self.canvasLayer.layer().previewAsPixmap( pm.size() ) icon.addPixmap( pm ) self.setIcon( 0, icon ) self.setToolTip( 0, self.canvasLayer.layer().publicSource() ) layerFont = QFont() layerFont.setBold( True ) self.setFont( 0, layerFont ) # Display layer properties self.properties = self.getLayerProperties( self.canvasLayer.layer() ) self.child = QTreeWidgetItem( self ) self.child.setFlags( Qt.NoItemFlags ) # Avoid the item to be selected self.displayLayerProperties()
def __init__(self, column, parent=None, pixmap=None): """ Class constructor. :param column: Column object containing foreign key information. :type column: BaseColumn :param parent: Parent widget for the control. :type parent: QWidget :param pixmap: Pixmap to use for the line edit button. :type pixmap: QPixmap """ QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity #Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = QPixmap(':/plugins/stdm/images/icons/select_record.png') if not pixmap is None: px = pixmap self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_load.clicked.connect(self.on_load_foreign_key_browser) #set minimum size frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) msz = self.minimumSizeHint() self.setMinimumSize( max(msz.width(), self.btn_load.sizeHint().height() + frame_width * 2 + 2), max(msz.height(), self.btn_load.sizeHint().height() + frame_width * 2 + 2)) #Ensure that text does not overlay button r_padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(r_padding) + 'px;') #Set layout layout = QHBoxLayout(self) layout.addWidget(self.btn_load, 0, Qt.AlignRight) layout.setSpacing(0) layout.setMargin(5) #Readonly as text is loaded from the related entity self.setReadOnly(True) #Current model object self._current_item = None
def _load_icon(filename, backgroundColor, width, height): foreground = QPixmap() foreground.load(filename) pixmap = QPixmap(foreground.size()) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) painter.drawPixmap(QPointF(0, 0), foreground) painter.end() pixmap = pixmap.scaled(QSize(width, height), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def __init__(self, *args, **kwargs): super(SearchEditor, self).__init__(*args, **kwargs) self.setPlaceholderText('Enter a search term') icon = QLabel(self) pixmap = QPixmap(asset('png', 'search.png')) icon.setPixmap(pixmap) icon.resize(pixmap.size()) self.searchicn = icon self.clearbtn = ClearButton(self) self.setTextMargins(30, 0, 30, 0) self.setFocusPolicy(Qt.NoFocus) self.current_vault = None self.queries = {}
def gifReceived(self, screen, data): pixmap = QPixmap() print "Data:", len(data) #, data[0:5], data[-3:] pixmap.loadFromData(data) s = pixmap.size() print "Size:", s.width(), s.height() if screen == 0: self.screen.setGraphsPixmap(pixmap) elif screen == 1: self.screen.setMenuPixmap(pixmap) elif screen == 2: self.screen.setStatusPixmap(pixmap)
def _welcome_window(self): widget = QLabel(self) pm = QPixmap(':icons/glue_welcome.png') pm = pm.scaledToHeight(400, mode=Qt.SmoothTransformation) widget.setPixmap(pm) widget.show() widget.resize(pm.size()) sub = self._add_to_current_tab(widget, label='Getting Started') def do_close(win): sub.close() self.current_tab.subWindowActivated.connect(do_close)
def store_data(self, id, data): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def get_favicon( host, ico_path): fail_pixmap = QPixmap(':/app/text-html.png') if not os.path.exists(ico_path): import urllib u = urllib.urlopen('http://favicon.yandex.net/favicon/%s'%host).read() #http://www.google.com/s2/favicons?domain=www.labnol.org tmp = open( '/tmp/tmp.png','w+b') tmp.write( u ) tmp.close() pixmap = QPixmap("/tmp/tmp.png") if pixmap.size() == QtCore.QSize(1, 1): pixmap = fail_pixmap tmp_ico = QIcon( pixmap ) pixmap.save( QString( ico_path) ) return tmp_ico
def initColour(self, colourstr, button, prefMethod): """ Public method to initialize a colour selection button. @param colourstr colour to be set (string) @param button reference to a QButton to show the colour on @param prefMethod preferences method to get the colour @return reference to the created colour (QColor) """ colour = QColor(prefMethod(colourstr)) size = button.size() pm = QPixmap(size.width()/2, size.height()/2) pm.fill(colour) button.setIconSize(pm.size()) button.setIcon(QIcon(pm)) return colour
class BttExport(Button): def __init__(self, img, parent=None): super(BttExport, self).__init__() self.pixmap = QPixmap( u"{img_media}{img}".format( img_media=Config.img_cmedia, img="{}.png".format(img))) self.setFixedHeight(85) self.setFixedWidth(85) def paintEvent(self, event): painter = QPainter(self) painter.drawPixmap(event.rect(), self.pixmap) def sizeHint(self): return self.pixmap.size()
def __init__(self, column, host=None, parent=None): # Use a different pixmap self._current_profile = current_profile() QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity self.layer = self.create_layer() self.host = host #Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = QPixmap(':/plugins/stdm/images/icons/expression.png') self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') frame_width = self.set_button_minimum_size(self.btn_load) # Ensure that text does not overlay button padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(padding * 2) + 'px;') # Set layout self.button_layout = QHBoxLayout(self) self.button_layout.addWidget(self.btn_load, 0, Qt.AlignRight) self.button_layout.setSpacing(0) self.button_layout.setMargin(5) # Readonly as text generated automatically self.setReadOnly(True) # Current model object self._current_item = None
def nextImage (self, *args): found_next= False while not found_next: fname= random.choice (self.files) print (fname) try: metadata= GExiv2.Metadata (fname) except GLib.Error as e: print (repr (e)) else: found_next= True img= QPixmap (fname) imgSize= self.rotate (metadata, img.size ()) self.item.setPixmap (img) # print (self.item.pos ().x(), self.item.pos ().y(), ) self.zoomFit (imgSize)
def showImage(self, file, md): self.metadata = md try: metadata = GExiv2.Metadata(file) except GLib.Error as e: print(repr(e)) return img = QPixmap(file) self.image.setPixmap(img) self.image.setScale(1.0) self.image.setRotation(0) imgSize = self.__rotate(metadata, img.size()) self.__zoomFit(imgSize) self.layoutMetadata()
def show(self): img = QPixmap(self.filename) try: metadata = GExiv2.Metadata(self.filename) except GLib.Error as e: print(repr(e)) return self.image.setPixmap(img) self.image.setScale(1.0) self.image.setRotation(0) imgSize = self.__rotate(metadata, img.size()) self.__zoomFit(imgSize) self.layoutText() self.title1.setVisible(True) self.title2.setVisible(True) self.title3.setVisible(True) self.image.setVisible(True)
class Display(QLabel): def __init__(self, parent=None): QLabel.__init__(self, parent) self._pixmap = QPixmap(PIXMAP_PATH) self.setFixedSize(self._pixmap.size()) #font = QFont() #font.setFamily(FONT) #font.setPointSize(7) #self.setFont(font) palette = self.palette() palette.setColor(QPalette.Text, COLOR) self.setPalette(palette) self.setMargin(2) #self.setIndent(2) self.setAlignment(Qt.AlignHCenter) def paintEvent(self, e): painter = QPainter(self) painter.drawPixmap(0, 0, QPixmap(PIXMAP_PATH)) rect = QRect(0, 0, self.width(), self.height()) painter.drawText(rect, Qt.AlignCenter, self.text()) painter.end()
def _add_file(self, fileinfo): '''docstring for _add_file''' thumb_size = 100 max_length_filename = thumb_size/9 path = fileinfo.filePath() px = QPixmap( path ) if px.size().isNull(): return filename = fileinfo.fileName() size = fileinfo.size() size_str = human( size ) if len(filename) > max_length_filename: filename = '%s...%s'%( filename[0:max_length_filename/2 ], filename[-max_length_filename/2:], ) else: filename = '%s'%( filename, ) text_item ="%(name)s \n [%(size)s]"%{'size': size_str, 'name':filename } icon = QIcon() icon.addPixmap( px.scaledToHeight( thumb_size ) ) data = { QString('path'): path , QString('size'): size, QString('human_size'): size_str, QString('fileinfo'):fileinfo, } item = QtGui.QListWidgetItem( icon, text_item, self.upload_list ) item.setData( QtCore.Qt.UserRole,QtCore.QVariant( data ) ) item.setToolTip( path) item.setSizeHint( QtCore.QSize( thumb_size+23,thumb_size+46) )
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect): global xscale, yscale self.rect = rect self.baseurl = self.mapurl(radar, rect, False) print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar,rect,markersonly): #'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = []; if len(ApiKeys.googleapi) > 0: urlp.append('key='+ApiKeys.googleapi) urlp.append('center='+str(radar['center'].lat)+','+str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width()/2,rsize.height()/2) zoom -= 1 urlp.append('zoom='+str(zoom)) urlp.append('size='+str(rsize.width())+'x'+str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append(str(marker['location'].lat)+','+str(marker['location'].lng)) urlp.append('markers='+'|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?'+'&'.join(urlp) def radarurl(self,radar,rect): #wuprefix = 'http://api.wunderground.com/api/'; #wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; #wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'],radar['zoom'],rect.width(),rect.height()) return (Config.wuprefix+ApiKeys.wuapi+'/animatedradar/image.gif'+ '?maxlat='+str(rr['N'])+ '&maxlon='+str(rr['E'])+ '&minlat='+str(rr['S'])+ '&minlon='+str(rr['W'])+ '&width='+str(rect.width())+ '&height='+str(rect.height())+ '&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1' ) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: return self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) self.wxmovie = QMovie(self.wxbuff, 'GIF') self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global manager self.wxreq = QNetworkRequest(QUrl(self.wxurl+'&rrrand='+str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"),self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply,QtCore.SIGNAL("finished()"),self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply,QtCore.SIGNAL("finished()"),self.mkfinished) def start(self, interval=10*60*1000): self.getbase() self.getmk() self.getwx() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer,QtCore.SIGNAL("timeout()"), self.getwx) self.timer.start(interval) def wxstart(self): self.wxmovie.start() def wxstop(self): self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
class ScreenShot(QWidget): def __init__(self): super(ScreenShot, self).__init__() self.initUI() def initUI(self): self.originalPixmap = QPixmap() self.screenshotLabel = QLabel("screenshotlabel", self) self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.screenshotLabel.setAlignment(Qt.AlignCenter) self.screenGeometry = QApplication.desktop().screenGeometry( ) # Qrect() print self.screenGeometry, self.screenGeometry.width() self.screenshotLabel.setMinimumSize(self.screenGeometry.width() / 8, self.screenGeometry.height() / 8) mainlayout = QVBoxLayout(self) mainlayout.addWidget(self.screenshotLabel) self.optionsGroupBox = QGroupBox(u"选项", self) self.hideThisWindowCheckBox = QCheckBox(u"隐藏这个窗口", self.optionsGroupBox) self.optionsGroupBoxLayout = QGridLayout(self.optionsGroupBox) mainlayout.addWidget(self.optionsGroupBox) self.delaySpinBox = QSpinBox(self.optionsGroupBox) self.delaySpinBox.setSuffix(u"s") self.delaySpinBox.setMaximum(60) self.optionsGroupBoxLayout.addWidget(QLabel(u"截屏延时:", self), 0, 0) self.optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1) self.optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0) buttonLayout = QHBoxLayout() self.newScreenshotButton = QPushButton(u"新截图", self) self.newScreenshotButton.clicked.connect(self.__newScreenshot) buttonLayout.addWidget(self.newScreenshotButton) saveScreenshotButton = QPushButton(u"保存截图", self) buttonLayout.addWidget(saveScreenshotButton) quitScreenshotButton = QPushButton(u"退出截图", self) quitScreenshotButton.setShortcut("Ctrl+Q") buttonLayout.addWidget(saveScreenshotButton) buttonLayout.addStretch() mainlayout.addLayout(buttonLayout) quitScreenshotButton.clicked.connect(self.close) saveScreenshotButton.clicked.connect(self.__saveScreenshot) self.delaySpinBox.valueChanged.connect(self.__updateCheckBox) self.delaySpinBox.setValue(5) self.setWindowTitle(u"截图") self.resize(300, 200) def resizeEvent(self, QResizeEvent): scaledSize = self.originalPixmap.size() scaledSize.scale(self.screenshotLabel.size(), Qt.KeepAspectRatio) if (not self.screenshotLabel.pixmap()) or ( scaledSize != self.screenshotLabel.pixmap().size()): self.__updateScreenshotLabel() def __newScreenshot(self): if self.hideThisWindowCheckBox.isChecked(): self.hide() self.newScreenshotButton.setDisabled(True) QTimer.singleShot(self.delaySpinBox.value() * 1000, self.__shootScreen) def __saveScreenshot(self): format = "png" initialPath = QDesktopServices.storageLocation( QDesktopServices.PicturesLocation) # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); if initialPath.isEmpty(): initialPath = QDir.currentPath() initialPath += "/untitled." + format fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath) fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) fileDialog.setFileMode(QtGui.QFileDialog.AnyFile) fileDialog.setDirectory(initialPath) mimeTypes = QStringList() for bf in QImageWriter.supportedImageFormats(): mimeTypes.append(QLatin1String(bf)) # fileDialog.setMin setMimeTypeFilters(mimeTypes) # fileDialog.selectMimeTypeFilter("image/" + format); fileDialog.setDefaultSuffix(format) if fileDialog.accept(): return fileName = fileDialog.selectedFiles().first() if not self.originalPixmap.save(fileName): QtGui.QMessageBox.Warning( self, u"保存错误", u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName))) def __shootScreen(self): if self.delaySpinBox.value() != 0: QApplication.beep() self.originalPixmap = QPixmap.grabWindow( QApplication.desktop().winId()) self.__updateScreenshotLabel() self.newScreenshotButton.setDisabled(False) if self.hideThisWindowCheckBox.isChecked(): self.show() def __updateCheckBox(self): print "sssss" if self.delaySpinBox.value() == 0: self.hideThisWindowCheckBox.setDisabled(True) self.hideThisWindowCheckBox.setChecked(False) else: self.hideThisWindowCheckBox.setDisabled(False) def __updateScreenshotLabel(self): self.screenshotLabel.setPixmap( self.originalPixmap.scaled(self.screenshotLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.baseurl = self.mapurl(radar, rect, False) #print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh*60 self.lastwx = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar,rect,markersonly): #'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = []; if len(ApiKeys.googleapi) > 0: urlp.append('key='+ApiKeys.googleapi) urlp.append('center='+str(radar['center'].lat)+','+str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width()/2,rsize.height()/2) zoom -= 1 urlp.append('zoom='+str(zoom)) urlp.append('size='+str(rsize.width())+'x'+str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append(str(marker['location'].lat)+','+str(marker['location'].lng)) urlp.append('markers='+'|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?'+'&'.join(urlp) def radarurl(self,radar,rect): #wuprefix = 'http://api.wunderground.com/api/'; #wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; #wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'],radar['zoom'],rect.width(),rect.height()) return (Config.wuprefix+ApiKeys.wuapi+'/animatedradar/image.gif'+ '?maxlat='+str(rr['N'])+ '&maxlon='+str(rr['E'])+ '&minlat='+str(rr['S'])+ '&minlon='+str(rr['W'])+ '&width='+str(rect.width())+ '&height='+str(rect.height())+ '&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1' ) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error "+self.myname+":"+str(self.wxreply.error()) self.lastwx = 0 return print "radar map received:"+self.myname+":"+time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:"+self.myname+":"+str(mov.frameCount()) if mov.frameCount() > 2: self.lastwx = time.time() else: # radar image retreval failed self.lastwx = 0 # retry in 5 seconds QtCore.QTimer.singleShot(5*1000, self.getwx) return self.wxmovie = mov self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global lastapiget i = 0.1 # making sure there is at least 2 seconds between radar api calls lastapiget += 2 if time.time() > lastapiget: lastapiget = time.time() else: i = lastapiget - time.time() print "get radar api call spacing oneshot get i="+str(i) QtCore.QTimer.singleShot(i*1000, self.getwx2) def getwx2(self): global manager try: if self.wxreply.isRunning(): return except Exception: pass print "getting radar map "+self.myname+":"+time.ctime() self.wxreq = QNetworkRequest(QUrl(self.wxurl+'&rrrand='+str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"),self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply,QtCore.SIGNAL("finished()"),self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply,QtCore.SIGNAL("finished()"),self.mkfinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.getmk() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer,QtCore.SIGNAL("timeout()"), self.getwx) def wxstart(self): print "wxstart for "+self.myname if (self.lastwx == 0 or (self.lastwx+self.interval) < time.time()): self.getwx() # random 1 to 10 seconds added to refresh interval to spread the queries over time i = (self.interval+random.uniform(1,10))*1000 self.timer.start(i) self.wxmovie.start() QtCore.QTimer.singleShot(1000, self.wxmovie.start) def wxstop(self): print "wxstop for "+self.myname self.timer.stop() self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.baseurl = self.mapurl(radar, rect, False) #print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh * 60 self.lastwx = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar, rect, markersonly): #'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = [] if len(ApiKeys.googleapi) > 0: urlp.append('key=' + ApiKeys.googleapi) urlp.append('center=' + str(radar['center'].lat) + ',' + str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width() / 2, rsize.height() / 2) zoom -= 1 urlp.append('zoom=' + str(zoom)) urlp.append('size=' + str(rsize.width()) + 'x' + str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append( str(marker['location'].lat) + ',' + str(marker['location'].lng)) urlp.append('markers=' + '|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?' + '&'.join( urlp) def radarurl(self, radar, rect): #wuprefix = 'http://api.wunderground.com/api/'; #wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; #wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'], radar['zoom'], rect.width(), rect.height()) return ( Config.wuprefix + ApiKeys.wuapi + '/animatedradar/image.gif' + '?maxlat=' + str(rr['N']) + '&maxlon=' + str(rr['E']) + '&minlat=' + str(rr['S']) + '&minlon=' + str(rr['W']) + '&width=' + str(rect.width()) + '&height=' + str(rect.height()) + '&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1' ) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error " + self.myname + ":" + str( self.wxreply.error()) self.lastwx = 0 return print "radar map received:" + self.myname + ":" + time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:" + self.myname + ":" + str( mov.frameCount()) if mov.frameCount() > 2: self.lastwx = time.time() else: # radar image retreval failed self.lastwx = 0 # retry in 5 seconds QtCore.QTimer.singleShot(5 * 1000, self.getwx) return self.wxmovie = mov self.wwx.setMovie(self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global lastapiget i = 0.1 # making sure there is at least 2 seconds between radar api calls lastapiget += 2 if time.time() > lastapiget: lastapiget = time.time() else: i = lastapiget - time.time() print "get radar api call spacing oneshot get i=" + str(i) QtCore.QTimer.singleShot(i * 1000, self.getwx2) def getwx2(self): global manager try: if self.wxreply.isRunning(): return except Exception: pass print "getting radar map " + self.myname + ":" + time.ctime() self.wxreq = QNetworkRequest( QUrl(self.wxurl + '&rrrand=' + str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"), self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply, QtCore.SIGNAL("finished()"), self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply, QtCore.SIGNAL("finished()"), self.mkfinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.getmk() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.getwx) def wxstart(self): print "wxstart for " + self.myname if (self.lastwx == 0 or (self.lastwx + self.interval) < time.time()): self.getwx() # random 1 to 10 seconds added to refresh interval to spread the queries over time i = (self.interval + random.uniform(1, 10)) * 1000 self.timer.start(i) self.wxmovie.start() QtCore.QTimer.singleShot(1000, self.wxmovie.start) def wxstop(self): print "wxstop for " + self.myname self.timer.stop() self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.anim = 5 self.zoom = radar["zoom"] self.point = radar["center"] self.radar = radar self.baseurl = self.mapurl(radar, rect) print "map base url: " + self.baseurl QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh * 60 self.lastwx = 0 self.retries = 0 self.corners = getCorners(self.point, self.zoom, rect.width(), rect.height()) self.baseTime = 0 self.cornerTiles = { "NW": getTileXY(LatLng(self.corners["N"], self.corners["W"]), self.zoom), "NE": getTileXY(LatLng(self.corners["N"], self.corners["E"]), self.zoom), "SE": getTileXY(LatLng(self.corners["S"], self.corners["E"]), self.zoom), "SW": getTileXY(LatLng(self.corners["S"], self.corners["W"]), self.zoom) } self.tiles = [] self.tiletails = [] self.totalWidth = 0 self.totalHeight = 0 self.tilesWidth = 0 self.tilesHeight = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) for y in range(int(self.cornerTiles["NW"]["Y"]), int(self.cornerTiles["SW"]["Y"]) + 1): self.totalHeight += 256 self.tilesHeight += 1 for x in range(int(self.cornerTiles["NW"]["X"]), int(self.cornerTiles["NE"]["X"]) + 1): tile = {"X": x, "Y": y} self.tiles.append(tile) tail = "/256/%d/%d/%d.png?color=3" % (self.zoom, x, y) self.tiletails.append(tail) for x in range(int(self.cornerTiles["NW"]["X"]), int(self.cornerTiles["NE"]["X"]) + 1): self.totalWidth += 256 self.tilesWidth += 1 self.frameImages = [] self.frameIndex = 0 self.displayedFrame = 0 self.ticker = 0 self.lastget = 0 def rtick(self): if time.time() > (self.lastget + self.interval): self.get(time.time()) self.lastget = time.time() if len(self.frameImages) < 1: return if self.displayedFrame == 0: self.ticker += 1 if self.ticker < 5: return self.ticker = 0 f = self.frameImages[self.displayedFrame] self.wwx.setPixmap(f["image"]) self.displayedFrame += 1 if self.displayedFrame >= len(self.frameImages): self.displayedFrame = 0 def get(self, t=0): t = int(t / 600) * 600 if t > 0 and self.baseTime == t: return if t == 0: t = self.baseTime else: self.baseTime = t newf = [] for f in self.frameImages: if f["time"] >= (t - self.anim * 600): newf.append(f) self.frameImages = newf firstt = t - self.anim * 600 for tt in range(firstt, t + 1, 600): print "get... " + str(tt) + " " + self.myname gotit = False for f in self.frameImages: if f["time"] == tt: gotit = True if not gotit: self.getTiles(tt) break def getTiles(self, t, i=0): t = int(t / 600) * 600 self.getTime = t self.getIndex = i if i == 0: self.tileurls = [] self.tileQimages = [] for tt in self.tiletails: tileurl = "https://tilecache.rainviewer.com/v2/radar/%d/%s" \ % (t, tt) self.tileurls.append(tileurl) print self.myname + " " + str(self.getIndex) + " " + self.tileurls[i] self.tilereq = QNetworkRequest(QUrl(self.tileurls[i])) self.tilereply = manager.get(self.tilereq) QtCore.QObject.connect(self.tilereply, QtCore.SIGNAL("finished()"), self.getTilesReply) def getTilesReply(self): print "getTilesReply " + str(self.getIndex) if self.tilereply.error() != QNetworkReply.NoError: return self.tileQimages.append(QImage()) self.tileQimages[self.getIndex].loadFromData(self.tilereply.readAll()) self.getIndex = self.getIndex + 1 if self.getIndex < len(self.tileurls): self.getTiles(self.getTime, self.getIndex) else: self.combineTiles() self.get() def combineTiles(self): global radar1 ii = QImage(self.tilesWidth * 256, self.tilesHeight * 256, QImage.Format_ARGB32) painter = QPainter() painter.begin(ii) painter.setPen(QColor(255, 255, 255, 255)) painter.setFont(QFont("Arial", 10)) i = 0 xo = self.cornerTiles["NW"]["X"] xo = int((int(xo) - xo) * 256) yo = self.cornerTiles["NW"]["Y"] yo = int((int(yo) - yo) * 256) for y in range(0, self.totalHeight, 256): for x in range(0, self.totalWidth, 256): painter.drawImage(x, y, self.tileQimages[i]) # painter.drawRect(x, y, 255, 255) # painter.drawText(x+3, y+12, self.tiletails[i]) i += 1 painter.end() painter = None self.tileQimages = [] ii2 = ii.copy(-xo, -yo, self.rect.width(), self.rect.height()) ii = None painter2 = QPainter() painter2.begin(ii2) timestamp = "{0:%H:%M} RainView.com".format( datetime.datetime.fromtimestamp(self.getTime)) painter2.setPen(QColor(63, 63, 63, 255)) painter2.setFont(QFont("Arial", 8)) painter2.setRenderHint(QPainter.TextAntialiasing) painter2.drawText(3 - 1, 12 - 1, timestamp) painter2.drawText(3 + 2, 12 + 1, timestamp) painter2.setPen(QColor(255, 255, 255, 255)) painter2.drawText(3, 12, timestamp) painter2.drawText(3 + 1, 12, timestamp) painter2.end() painter2 = None ii3 = QPixmap(ii2) ii2 = None self.frameImages.append({"time": self.getTime, "image": ii3}) ii3 = None def mapurl(self, radar, rect): mb = 0 try: mb = Config.usemapbox except: pass if mb: return self.mapboxurl(radar, rect) else: return self.googlemapurl(radar, rect) def mapboxurl(self, radar, rect): # note we're using google maps zoom factor. # Mapbox equivilant zoom is one less # They seem to be using 512x512 tiles instead of 256x256 style = 'mapbox/satellite-streets-v10' if 'style' in radar: style = radar['style'] return 'https://api.mapbox.com/styles/v1/' + \ style + \ '/static/' + \ str(radar['center'].lng) + ',' + \ str(radar['center'].lat) + ',' + \ str(radar['zoom']-1) + ',0,0/' + \ str(rect.width()) + 'x' + str(rect.height()) + \ '?access_token=' + ApiKeys.mbapi def googlemapurl(self, radar, rect): urlp = [] if len(ApiKeys.googleapi) > 0: urlp.append('key=' + ApiKeys.googleapi) urlp.append('center=' + str(radar['center'].lat) + ',' + str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width() / 2, rsize.height() / 2) zoom -= 1 urlp.append('zoom=' + str(zoom)) urlp.append('size=' + str(rsize.width()) + 'x' + str(rsize.height())) urlp.append('maptype=hybrid') return 'http://maps.googleapis.com/maps/api/staticmap?' + \ '&'.join(urlp) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) # make marker pixmap self.mkpixmap = QPixmap(self.basepixmap.size()) self.mkpixmap.fill(Qt.transparent) br = QBrush(QColor(Config.dimcolor)) painter = QPainter() painter.begin(self.mkpixmap) painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(), br) for marker in self.radar['markers']: pt = getPoint(marker["location"], self.point, self.zoom, self.rect.width(), self.rect.height()) mk2 = QImage() mkfile = 'teardrop' if 'image' in marker: mkfile = marker['image'] if os.path.dirname(mkfile) == '': mkfile = os.path.join('markers', mkfile) if os.path.splitext(mkfile)[1] == '': mkfile += '.png' mk2.load(mkfile) if mk2.format != QImage.Format_ARGB32: mk2 = mk2.convertToFormat(QImage.Format_ARGB32) mkh = 80 # self.rect.height() / 5 if 'size' in marker: if marker['size'] == 'small': mkh = 64 if marker['size'] == 'mid': mkh = 70 if marker['size'] == 'tiny': mkh = 40 if 'color' in marker: c = QColor(marker['color']) (cr, cg, cb, ca) = c.getRgbF() for x in range(0, mk2.width()): for y in range(0, mk2.height()): (r, g, b, a) = QColor.fromRgba(mk2.pixel(x, y)).getRgbF() r = r * cr g = g * cg b = b * cb mk2.setPixel(x, y, QColor.fromRgbF(r, g, b, a).rgba()) mk2 = mk2.scaledToHeight(mkh, 1) painter.drawImage(pt.x - mkh / 2, pt.y - mkh / 2, mk2) painter.end() self.wmk.setPixmap(self.mkpixmap) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply, QtCore.SIGNAL("finished()"), self.basefinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.rtick) self.lastget = time.time() - self.interval + random.uniform(3, 10) def wxstart(self): print "wxstart for " + self.myname self.timer.start(200) def wxstop(self): print "wxstop for " + self.myname self.timer.stop() def stop(self): try: self.timer.stop() self.timer = None except Exception: pass
def __init__(self, controller, *args, **kwargs): self.controller = controller self.wget_retcode = None self.wget_proc = None if self.controller.oem_user_config: self.only = True else: self.only = False try: from PyQt4 import uic from PyQt4.QtGui import QWidget, QPixmap self.page = uic.loadUi('/usr/share/ubiquity/qt/stepLanguage.ui') self.combobox = self.page.language_combobox self.combobox.currentIndexChanged[str].connect( self.on_language_selection_changed) if not self.controller.oem_config: self.page.oem_id_label.hide() self.page.oem_id_entry.hide() def inst(*args): self.page.try_ubuntu.setEnabled(False) self.controller.go_forward() self.page.install_ubuntu.clicked.connect(inst) self.page.try_ubuntu.clicked.connect(self.on_try_ubuntu_clicked) picture1 = QPixmap( "/usr/share/ubiquity/pixmaps/kubuntu-live-session.png") self.page.image1.setPixmap(picture1) self.page.image1.resize(picture1.size()) picture2 = QPixmap( "/usr/share/ubiquity/pixmaps/kubuntu-install.png") self.page.image2.setPixmap(picture2) self.page.image2.resize(picture2.size()) self.release_notes_url = '' self.update_installer = True self.updating_installer = False if self.controller.oem_config or auto_update.already_updated(): self.update_installer = False self.release_notes_found = False try: with open(_release_notes_url_path) as release_notes: self.release_notes_url = release_notes.read().rstrip('\n') self.release_notes_found = True except (KeyboardInterrupt, SystemExit): raise except: pass if self.release_notes_url: self.page.release_notes_label.linkActivated.connect( self.on_release_notes_link) else: self.page.release_notes_label.hide() if not 'UBIQUITY_GREETER' in os.environ: self.page.try_ubuntu.hide() self.page.try_install_text_label.hide() self.page.install_ubuntu.hide() self.page.image1.hide() self.page.image2.hide() if self.only: self.page.alpha_warning_label.hide() # We do not want to show the yet to be substituted strings # (${MEDIUM}, etc), so don't show the core of the page until # it's ready. self.widgetHidden = [] for w in self.page.children(): if isinstance(w, QWidget) and not w.isHidden(): self.widgetHidden.append(w) w.hide() except Exception as e: self.debug('Could not create language page: %s', e) self.page = None self.plugin_widgets = self.page
def __init__(self, column, parent=None, pixmap=None, host=None): """ Class constructor. :param column: Column object containing foreign key information. :type column: BaseColumn :param parent: Parent widget for the control. :type parent: QWidget :param pixmap: Pixmap to use for the line edit button. :type pixmap: QPixmap """ QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity self.entity_dialog = host #Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = QPixmap(':/plugins/stdm/images/icons/select_record.png') if not pixmap is None: px = pixmap self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_load.clicked.connect(self.on_load_foreign_key_browser) clear_px = QPixmap(':/plugins/stdm/images/icons/clear.png') self.btn_clear = QToolButton(parent) self.btn_clear.setCursor(Qt.PointingHandCursor) self.btn_clear.setFocusPolicy(Qt.NoFocus) self.btn_clear.setIcon(QIcon(clear_px)) self.btn_clear.setIconSize(clear_px.size()) self.btn_clear.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_clear.clicked.connect(self.clear_line_edit) frame_width = self.set_button_minimum_size(self.btn_load) self.set_button_minimum_size(self.btn_clear) # Ensure that text does not overlay button padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(padding * 2) + 'px;') # Set layout self.button_layout = QHBoxLayout(self) self.button_layout.addWidget(self.btn_clear, 0, Qt.AlignRight) self.button_layout.addWidget(self.btn_load, 0, Qt.AlignRight) self.button_layout.setSpacing(0) self.button_layout.setMargin(5) self.btn_clear.setVisible(False) # Readonly as text is loaded from the related entity self.setReadOnly(True) # Current model object self._current_item = None
def __init__(self, *args, **kwargs): super(ClearButton, self).__init__(*args, **kwargs) pixmap = QPixmap(asset('png', 'clear.png')) self.setPixmap(pixmap) self.resize(pixmap.size()) self.setCursor(Qt.ArrowCursor)
def init_big_button(button, image_name): pix = QPixmap('/usr/share/ubiquity/qt/images/' + image_name) icon = QIcon(pix) button.setIcon(icon) button.setIconSize(pix.size())
class main(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("Images!") ## Create BackGround to Load images into self.bg = QLabel(self) self.bg.move(0, 30) self.bg.resize(400, 550) self.bg.setStyleSheet("background-color: black;") self.setGeometry(100, 100, 400, 600) self.button = QLabel("Open..", self) self.button.setFixedSize(55, 24) self.button.setStyleSheet("border: 1px solid black; font-size: 15px") self.button. move(330, 2) self.button.mousePressEvent = self.open_label ## Create File QAction for MenuBar openFileAction = QAction('&Open Image...', self) openFileAction.setShortcut('Ctrl+O') openFileAction.setStatusTip('Open Image File') ## Connect to the open_image function openFileAction.triggered.connect(self.open_file) #Exit Action exitAction = QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.triggered.connect(app.quit) ## Create Menu Bar and Add File Menu to it self.menubar = self.menuBar() self.file_menu = self.menubar.addMenu("&File") ## Link the File Menu to the QActions. self.file_menu.addAction(openFileAction) self.file_menu.addAction(exitAction) def open_label(self, event): self.open_file() def open_file(self): filename = QFileDialog.getOpenFileName() print filename ## import Image as a QPixMap self.bg_img = QPixmap(filename) ## Resize Window to the Size of opened image self.setFixedSize(self.bg_img.size()) #<---~ 'self is the QMainWindow' self.bg.setFixedSize(self.bg_img.size()) ## set the Image to the background QLabel self.bg.setPixmap(self.bg_img) self.button.move(int(self.bg_img.width()) - 70, 2)
class Preview(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pixmap = QPixmap() # Flag indicating if the widget was resized as a result of user # initiated window resize. When false the widget will automatically # resize/re-position based on pixmap size. self.__hasExplicitSize = False self.__inUpdateWindowGeometry = False def setPixmap(self, pixmap): if self.__pixmap != pixmap: self.__pixmap = QPixmap(pixmap) self.__updateWindowGeometry() self.update() self.updateGeometry() def pixmap(self): return QPixmap(self.__pixmap) def resizeEvent(self, event): super().resizeEvent(event) if self.isVisible() and self.isWindow() and \ not self.__inUpdateWindowGeometry: # mark that we have an explicit user provided size self.__hasExplicitSize = True def __updateWindowGeometry(self): if not self.isWindow() or self.__hasExplicitSize: return def framemargins(widget): frame, geom = widget.frameGeometry(), widget.geometry() return QMargins(geom.left() - frame.left(), geom.top() - frame.top(), geom.right() - frame.right(), geom.bottom() - frame.bottom()) def fitRect(rect, targetrect): size = rect.size().boundedTo(targetgeom.size()) newrect = QRect(rect.topLeft(), size) dx, dy = 0, 0 if newrect.left() < targetrect.left(): dx = targetrect.left() - newrect.left() if newrect.top() < targetrect.top(): dy = targetrect.top() - newrect.top() if newrect.right() > targetrect.right(): dx = targetrect.right() - newrect.right() if newrect.bottom() > targetrect.bottom(): dy = targetrect.bottom() - newrect.bottom() return newrect.translated(dx, dy) margins = framemargins(self) minsize = QSize(120, 120) pixsize = self.__pixmap.size() available = QApplication.desktop().availableGeometry(self) available = available.adjusted(margins.left(), margins.top(), -margins.right(), -margins.bottom()) # extra adjustment so the preview does not cover the whole desktop available = available.adjusted(10, 10, -10, -10) targetsize = pixsize.boundedTo(available.size()).expandedTo(minsize) pixsize.scale(targetsize, Qt.KeepAspectRatio) if not self.testAttribute(Qt.WA_WState_Created) or \ self.testAttribute(Qt.WA_WState_Hidden): center = available.center() else: center = self.geometry().center() targetgeom = QRect(QPoint(0, 0), pixsize) targetgeom.moveCenter(center) if not available.contains(targetgeom): targetgeom = fitRect(targetgeom, available) self.__inUpdateWindowGeometry = True self.setGeometry(targetgeom) self.__inUpdateWindowGeometry = False def sizeHint(self): return self.__pixmap.size() def paintEvent(self, event): if self.__pixmap.isNull(): return sourcerect = QRect(QPoint(0, 0), self.__pixmap.size()) pixsize = QSizeF(self.__pixmap.size()) rect = self.contentsRect() pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio) targetrect = QRectF(QPointF(0, 0), pixsize) targetrect.moveCenter(QPointF(rect.center())) painter = QPainter(self) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect)) painter.end()
class pngDisplay(QWidget): def __init__(self, parent=None): super(pngDisplay, self).__init__(parent) #self.profiler = cProfile.Profile() # create the label that displays the image - cribbing from the Image # Viewer example in the Qt docs. self.imLabel = QLabel() self.imLabel.setBackgroundRole(QPalette.Base) self.imLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imLabel.setScaledContents(True) # Create a gray field to use when no png is available self.defaultPM = QPixmap(700,900) self.defaultPM.fill(QColor("gray")) # Create a scroll area within which to display our imLabel, this # enables the creation of horizontal and vertical scroll bars, when # the imLabel exceeds the size of the scroll area. self.scarea = QScrollArea() # The following two lines make sure that page up/dn gets through # the scrollarea widget and up to us. self.setFocusPolicy(Qt.ClickFocus) self.scarea.setFocusProxy(self) self.scarea.setBackgroundRole(QPalette.Dark) #self.scarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) #self.scarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.scarea.setWidget(self.imLabel) # create the text label that will have the page number in it self.txLabel = QLabel(u"No image") self.txLabel.setAlignment(Qt.AlignBottom | Qt.AlignHCenter) self.txLabel.setFrameStyle(QFrame.Sunken | QFrame.StyledPanel) # Create a spinbox to set the zoom from 15 to 200 with a label: # (originally a slider, hence the name) self.minZoom = 0.15 self.maxZoom = 2.00 self.zlider = QSpinBox() self.zlider.setRange(int(100*self.minZoom),int(100*self.maxZoom)) # connect the value change signal to a slot to handle it self.connect(self.zlider, SIGNAL("valueChanged(int)"), self.newZoomFactor) # create the to-width and to-height zoom buttons zoomWidthButton = QPushButton(u'to Width') self.connect(zoomWidthButton, SIGNAL("clicked()"), self.zoomToWidth) zoomHeightButton = QPushButton(u'to Height') self.connect(zoomHeightButton, SIGNAL("clicked()"), self.zoomToHeight) # Make an hbox to contain the spinbox and two pushbuttons, with # stretch on left and right to center the group. zlabel = QLabel( u'&Zoom ' + str(self.zlider.minimum()) + '-' + str(self.zlider.maximum()) + '%') zlabel.setBuddy(self.zlider) zhbox = QHBoxLayout() zhbox.addStretch(1) zhbox.addWidget(zlabel,0,Qt.AlignLeft) zhbox.addWidget(self.zlider,0) zhbox.addStretch(1) zhbox.addWidget(zoomWidthButton) zhbox.addWidget(zoomHeightButton) zhbox.addStretch(1) # With all the pieces in hand, create our layout basically a # vertical stack: scroll area, label, slider box. vbox = QVBoxLayout() # the image gets a high stretch and default alignment, the text # label hugs the bottom and doesn't stretch at all. vbox.addWidget(self.txLabel,0,Qt.AlignBottom) vbox.addWidget(self.scarea,10) vbox.addLayout(zhbox,0) self.setLayout(vbox) # Initialize assuming no book is open. self.ready = False # nothing to display # Recover the last-set zoom factor from the settings object, default 1.0 qv = IMC.settings.value("pngs/zoomFactor",QVariant(1.0)) self.zoomFactor = qv.toFloat()[0] # The following causes entry into newZoomFactor, below, which tests # self.ready, hence the latter has to be assigned-to first. self.zlider.setValue(int(self.zoomFactor*100)) self.clear() # local subroutine to initialize our contents for an empty edit. # called from _init_ and from newPosition when we discover the file # has been cleared on us. Don't reset the zoomFactor, leave it as # the user last set it. def clear(self): # Clear the page name, used by pqNotes IMC.currentImageNumber = None # will be name of last png file e.g. "002" # Clear the page filename, used in our caption label self.lastPage = QString() # last file name e.g. "002.png" # Clear the path to the pngs folder, used to fetch image files self.pngPath = QString() # Clear the index of the last-shown page in the page table # -1 means no page is being displayed. self.lastIndex = -1 # Clear the index of the next page to display, normally same as last self.nextIndex = -1 # Set not-ready to indicate no pngs directory available. self.ready = False # Clear out & release storage of our QImage and QPixmaps self.pixmap = QPixmap() # null pixmap self.image = QImage() self.noImage() # show gray image # Display a blank gray frame and "No Image" below. # Called from clear() above and from showPage when no valid image. def noImage(self) : self.imLabel.setPixmap(self.defaultPM) self.txLabel.setText(u"No image") self.lastIndex = -1 # didn't see a prior page self.nextIndex = -1 # This slot gets the main window's signal shuttingDown. # We save our current zoom factor into IMC.settings. def shuttingDown(self): IMC.settings.setValue("pngs/zoomFactor",QVariant(self.zoomFactor)) # This slot gets pqMain's signal docHasChanged(QString), telling # us that a different document has been loaded. This could be for # a successful File>Open, or a failed File>Open or File>New. # The bookPath is a null QString for File>New, or the full bookPath. # If the latter, we convert that into the path to the pngs folder, # and see if bookPath/pngs is a directory. If so, we set self.ready # to true, indicating it is worthwhile to try opening image files. # At this point the gray image is displayed and previously would remain displayed # until the user moved the cursor in some way, generating cursorPositionChanged. # That's a minor annoyance, to avoid it we will fake that signal now. def newFile(self, bookPath): if not bookPath.isNull(): # this was successful File>Open finf = QFileInfo(bookPath) self.pngPath = finf.absolutePath().append(u"/pngs/") finf = QFileInfo(self.pngPath) if finf.exists() and finf.isDir(): # looking good self.ready = True self.newPosition() else: # We could inform the user we couldn't find a pngs folder, # but you know -- the user is probably already aware of that. self.clear() # just put up the gray default image else: # It was a File>New self.clear() # This function is the slot that is connected to the editor's # cursorPositionChanged signal. Its input is cursor position and # the page table. Its output is to set self.nextIndex to the # desired next image table row, and to call showPage. def newPosition(self): if self.ready : # We have a book and some pngs. Find the position of the higher end # of the current selection. pos = IMC.editWidget.textCursor().selectionEnd() # Get the page table index that matches this position, or -1 # if that is above the first psep, or there is no page data self.nextIndex = IMC.pageTable.getIndex(pos) else :# No file loaded or no pngs folder found. self.nextIndex = -1 if self.nextIndex != self.lastIndex : self.showPage() # Display the page indexed by self.nextIndex. This is called when the cursor # moves to a new page (newPosition, above), or when the PageUp/Dn keys are used, # (keyPressEvent, below) or when the zoom factor changes in any of several ways. def showPage(self): # If self.lastIndex is different from self.nextIndex, the page has # changed, and we need to load a new image. if self.lastIndex != self.nextIndex : self.lastIndex = self.nextIndex # don't come here again until it changes. if self.lastIndex > -1 : # Form the image filename as a Qstring, e.g. "025" and save that for # use by pqNotes: IMC.currentImageNumber = IMC.pageTable.getScan(self.lastIndex) # dbg = unicode(IMC.currentImageNumber) # Form the complete filename by appending ".png" and save as # self.lastPage for use in forming our caption label. self.lastPage = QString(IMC.currentImageNumber).append(QString(u".png")) # dbg = unicode(self.lastPage) # Form the full path to the image. Try to load it as a QImage. pngName = QString(self.pngPath).append(self.lastPage) self.image = QImage(pngName,'PNG') # dbg = unicode(self.image) # dbg = self.image.isNull() # If that successfully loaded an image, make sure it is one byte/pixel. if not self.image.isNull() \ and self.image.format() != QImage.Format_Indexed8 : # It might be Format_Mono (1 bit/pixel) or even Format_RGB32. self.image = self.image.convertToFormat(QImage.Format_Indexed8,Qt.ColorOnly) # Convert the image to a pixmap. If it's null, so is the pixmap. self.pixmap = QPixmap.fromImage(self.image,Qt.ColorOnly) else : IMC.currentImageNumber = QString(u"n.a.") self.lastPage = QString() self.image = QImage() self.pixmap = QPixmap() if not self.pixmap.isNull(): # We successfully found and loaded an image and converted it to pixmap. # Load it in our label for display, set the zoom factor, and the caption. # We do this every time through (even if lastIndex equalled nextIndex) # because the zoomfactor might have changed. self.imLabel.setPixmap(self.pixmap) self.imLabel.resize( self.zoomFactor * self.pixmap.size() ) folio = IMC.pageTable.getDisplay(self.lastIndex) self.txLabel.setText(u"image {0} (folio {1})".format(self.lastPage,folio)) else: # no file was loaded. It's ok if pages are missing self.noImage() # display the gray image. # Catch the signal from the Zoom spinbox with a new value. # Store the new value as a float, and if we have a page, repaint it. def newZoomFactor(self,new_value): self.zoomFactor = new_value / 100 if self.ready : self.showPage() # Catch the click on zoom-to-width and zoom-to height. The job is basically # the same for both. 1: Using the QImage that should be in self.image, # scan the pixels to find the width (height) of the nonwhite area. # 2. Get the ratio of that to our image label's viewport width (height). # 4. Set that ratio as the zoom factor and redraw the image. And finally # 5. Set the scroll position(s) of our scroll area to left-justify the text. # # We get access to the pixels using QImage:bits() which gives us a PyQt4 # "voidptr" that we can index to get byte values. # def zoomToWidth(self): if (not self.ready) or (self.image.isNull()) : return # nothing to do here #self.profiler.enable() #dbg # Query the Color look-up table and build a list of the Green values # corresponding to each possible pixel value. Probably there are just # two colors so colortab is [0,255] but there could be more, depending # on how the PNG was defined, 16 or 32 or even 255 grayscale. colortab = [ int((self.image.color(c) >> 4) & 255) for c in range(self.image.colorCount()) ] ncols = self.image.width() # number of logical pixels across stride = (ncols + 3) & (-4) # number of bytes per scanline nrows = self.image.height() # number of pixels high vptr = self.image.bits() # uchar * bunch-o-pixel-bytes vptr.setsize(stride * nrows) # make the pointer indexable # Scan in from left and right to find the outermost dark spots. # Looking for single pixels yeilds too many false positives, so we # look for three adjacent pixels that sum to less than 32. # Most pages start with many lines of white pixels so in hopes of # establishing the outer edge early, we start at the middle, go to # the end, then do the top half. left_side = int(ncols/2) # leftmost dark spot seen so far # scan from the middle down for r in xrange(int(nrows/2)*stride, (nrows-1)*stride, stride) : pa, pb = 255, 255 # virtual white outside border for c in xrange(left_side): pc = colortab[ ord(vptr[c + r]) ] if (pa + pb + pc) < 32 : # black or dark gray pair left_side = c # new, further-left, left margin break # no need to look further on this line pa = pb pb = pc # scan from the top to the middle, hopefully left_side is small now for r in xrange(0, int(nrows/2)*stride, stride) : pa, pb = 255, 255 # virtual white outside border for c in xrange(left_side): pc = colortab[ ord(vptr[c + r]) ] if (pa + pb + pc) < 32 : # black or dark gray pair left_side = c # new, further-left, left margin break # no need to look further on this line pa = pb pb = pc # Now do the same for the right margin. right_side = int(ncols/2) # rightmost dark spot seen so far for r in xrange(int(nrows/2)*stride, (nrows-1)*stride, stride) : pa, pb = 255, 255 # virtual white outside border for c in xrange(ncols-1,right_side,-1) : pc = colortab[ ord(vptr[c + r]) ] if (pa + pb + pc) < 32 : # black or dark gray pair right_side = c # new, further-right, right margin break pa = pb pb = pc for r in xrange(0, int(nrows/2)*stride, stride) : pa, pb = 255, 255 # virtual white outside border for c in xrange(ncols-1,right_side,-1) : pc = colortab[ ord(vptr[c + r]) ] if (pa + pb + pc) < 32 : # black or dark gray pair right_side = c # new, further-right, right margin break pa = pb pb = pc # The area with color runs from left_side to right_side. How does # that compare to the size of our viewport? Scale to that and redraw. #print('ls {0} rs {1} vp {2}'.format(left_side,right_side,self.scarea.viewport().width())) text_size = right_side - left_side + 2 port_width = self.scarea.viewport().width() self.zoomFactor = max( self.minZoom, min( self.maxZoom, port_width / text_size ) ) # the next line signals newZoomFactor, which calls showPage. self.zlider.setValue(int(100*self.zoomFactor)) # Set the scrollbar to show the page from its left margin. self.scarea.horizontalScrollBar().setValue(int( left_side * self.zoomFactor) ) #self.profiler.disable() #dbg #pstats.Stats(self.profiler).print_stats() # dbg def zoomToHeight(self): if (not self.ready) or (self.image.isNull()) : return # nothing to do here # Query the Color look-up table and build a list of the Green values # corresponding to each possible pixel value. Probably there are just # two colors so colortab is [0,255] but there could be more, depending # on how the PNG was defined, 16 or 32 or even 255 grayscale. colortab = [ int((self.image.color(c) >> 4) & 255) for c in range(self.image.colorCount()) ] ncols = self.image.width() # number of logical pixels across stride = (ncols + 3) & (-4) # number of bytes per scanline nrows = self.image.height() # number of pixels high vptr = self.image.bits() # uchar * bunch-o-pixel-bytes vptr.setsize(stride * nrows) # make the pointer indexable # Scan in from top and bottom to find the outermost rows with # significant pixels. top_side = -1 # The uppermost row with a significant spot of black offset = 0 # vptr index to the first/next pixel row for r in range(nrows) : pa, pb = 255, 255 # virtual white outside border for c in range(ncols) : pc = colortab[ ord(vptr[offset + c]) ] if (pa + pb + pc) < 32 : # black or dark gray triplet top_side = r # that's the row, break # ..so stop scanning pa, pb = pb, pc if top_side >= 0 : # we hit break # ..so don't scan down any further offset += stride # continue to next row # top_side indexes the first row with a significant blot if top_side == -1 : # never found one: an all-white page. bug out. return bottom_side = nrows # The lowest row with a significant blot offset = stride * nrows # vptr index to last/next row of pixels for r in range(nrows,top_side,-1) : offset -= stride pa, pb = 255, 255 # virtual white outside border for c in range(ncols) : pc = colortab[ ord(vptr[offset + c]) ] if (pa + pb + pc) < 32 : # black or dark gray triplet bottom_side = r break pa, pb = pb, pc if bottom_side < nrows : # we hit break # bottom_side is the lowest row with significant pixels. It must be # < nrows, there is at least one row (top_side) with a dot in it. # However if the page is mostly white, don't zoom to that extent. if bottom_side < (top_side+100) : return # seems to be a mostly-white page, give up # The text area runs from scanline top_side to bottom_side. text_height = bottom_side - top_side + 1 port_height = self.scarea.viewport().height() self.zoomFactor = max( self.minZoom, min( self.maxZoom, port_height / text_height ) ) self.zlider.setValue(int(100*self.zoomFactor)) # signals newZoomFactor->showPage # Set the scrollbar to show the page from its top margin. self.scarea.verticalScrollBar().setValue(int( top_side * self.zoomFactor) ) # Re-implement the parent's keyPressEvent in order to provide zoom: # ctrl-plus increases the image size by 1.25 # ctrl-minus decreases the image size by 0.8 # Also trap pageup/dn and use to walk through images. # At this point we do not reposition the editor to match the page viewed. # we page up/dn but as soon as focus returns to the editor and the cursor # moves, this display will snap back to the edited page. As a user that # seems best, come over to Pngs and page ahead to see what's coming, then # back to the editor to read or type. def keyPressEvent(self, event): # assume we will not handle this key and clear its accepted flag event.ignore() # If we are initialized and have displayed some page, look at the key if self.ready: kkey = int( int(event.modifiers()) & IMC.keypadDeModifier) | int(event.key()) if kkey in IMC.zoomKeys : # ctl/cmd + or -, do the zoom event.accept() fac = (0.8) if (kkey == IMC.ctl_minus) else (1.25) fac *= self.zoomFactor # target zoom factor if (fac >= self.minZoom) and (fac <= self.maxZoom): # keep in bounds self.zoomFactor = fac self.zlider.setValue(int(100*fac)) self.showPage() elif (event.key() == Qt.Key_PageUp) or (event.key() == Qt.Key_PageDown) : event.accept() # real pgUp or pgDn, we do it fac = 1 if (event.key() == Qt.Key_PageDown) else -1 fac += self.lastIndex if (fac >= 0) and (fac < IMC.pageTable.size()) : # not off either end of the book, so, self.nextIndex = fac self.showPage() if not event.isAccepted() : # we don't do those, pass them on super(pngDisplay, self).keyPressEvent(event)