def paint(self, painter, option, index): painter.save() index0 = index.sibling( index.row(), 0 ) utype = index0.data( Qt.UserRole ) # # set background color if option.state & QStyle.State_Selected: painter.setPen ( Qt.NoPen ) painter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushSelected ) painter.drawRect(option.rect) elif option.state & QStyle.State_MouseOver: painter.setPen ( Qt.NoPen ) painter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushHovered ) painter.drawRect(option.rect) rect = option.rect icon = QIcon( index.data( Qt.DecorationRole) ) rect.adjust( 5, 0, 0, 0 ) if icon and not icon.isNull(): icon.paint( painter, rect, Qt.AlignLeft ) rect.adjust( 22, 0, 0, 0 ) text = index.data(Qt.DisplayRole) if utype == 1: #GROUP painter.setPen( SceneGraphTreeItemDelegate._textPenGroup ) else: painter.setPen( SceneGraphTreeItemDelegate._textPen ) painter.drawText( rect, Qt.AlignLeft | Qt.AlignVCenter, text ) painter.restore()
def paint(self, painter, option, index): painter.save() index0 = index.sibling(index.row(), 0) utype = index0.data(Qt.UserRole) # # set background color if option.state & QStyle.State_Selected: painter.setPen(Qt.NoPen) painter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushSelected) painter.drawRect(option.rect) elif option.state & QStyle.State_MouseOver: painter.setPen(Qt.NoPen) painter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushHovered) painter.drawRect(option.rect) rect = option.rect icon = QIcon(index.data(Qt.DecorationRole)) rect.adjust(5, 0, 0, 0) if icon and not icon.isNull(): icon.paint(painter, rect, Qt.AlignLeft) rect.adjust(22, 0, 0, 0) text = index.data(Qt.DisplayRole) if utype == 1: #GROUP painter.setPen(SceneGraphTreeItemDelegate._textPenGroup) else: painter.setPen(SceneGraphTreeItemDelegate._textPen) painter.drawText(rect, Qt.AlignLeft | Qt.AlignVCenter, text) painter.restore()
def load(self, name, size=128, forceCache=False): icon = QIcon() size = int(size) self.pixmap = QPixmap() if not type(name) in (list, tuple): name = [str(name)] if forceCache or self._forceCache: for _name in name: for _size in self.iconSizes: if (QPixmapCache.find('$qt' + str(_name) + str(_size), self.pixmap)): logging.debug('Icon %s returned from cache' % _name) return self.pixmap logging.debug('Getting icon : %s size: %s' % (','.join(name), size)) pix = self.findIcon(name, size) if pix.isNull(): for _size in self.iconSizes: pix = self.findIcon(name, _size) if not pix.isNull(): if size == _size: return pix icon.addPixmap(pix) if icon.isNull(): return self.pixmap return icon.pixmap(QSize(size, size)) return pix
def load(self, name, size = 128, forceCache = False): icon = QIcon() size = int(size) self.pixmap = QPixmap() if not type(name) in (list, tuple): name = [str(name)] if forceCache or self._forceCache: for _name in name: for _size in self.iconSizes: if (QPixmapCache.find('$qt'+str(_name)+str(_size), self.pixmap)): logging.debug('Icon %s returned from cache' % _name) return self.pixmap logging.debug('Getting icon : %s size: %s' % (','.join(name), size)) pix = self.findIcon(name, size) if pix.isNull(): for _size in self.iconSizes: pix = self.findIcon(name, _size) if not pix.isNull(): if size == _size: return pix icon.addPixmap(pix) if icon.isNull(): return self.pixmap return icon.pixmap(QSize(size, size)) return pix
def setHoverIcon(self, icon): """ Sets the icon that will be used when this hotspot is hovered. :param icon | <QIcon> || None """ icon = QIcon(icon) if not icon.isNull(): self._hoverIcon = QIcon(icon) else: self._hoverIcon = None
def getShortcutIcon(shortcut): if shortcut["icon"]: icon = QIcon(shortcut["icon"]) if not icon.isNull(): return icon iconProvider = QFileIconProvider() if shortcut["path"] == COMPUTER_PATH: return QIcon(":/images/user-home.png") elif shortcut["path"] == DOCUMENTS_PATH: documentsIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation))) if documentsIcon.isNull(): return QIcon(":/images/folder-documents.png") else: return documentsIcon elif shortcut["path"] == MUSIC_PATH: musicIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.MusicLocation))) if musicIcon.isNull(): return QIcon(":/images/folder-sound.png") else: return musicIcon elif shortcut["path"] == PICTURES_PATH: picturesIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.PicturesLocation))) if picturesIcon.isNull(): return QIcon(":/images/folder-image.png") else: return picturesIcon else: url = QUrl.fromUserInput(shortcut["path"]) if url.scheme() == "file": if os.path.exists(shortcut["path"]): icon = iconProvider.icon(QFileInfo(url.toLocalFile())) if not icon.isNull(): return icon return QIcon(":/images/unknown.png") else: return QIcon(":/images/httpurl.png") return QIcon(":/images/unknown.png")
def setIcon(self, icon): """ Sets the icon for this hotspot. If this method is called with a valid icon, then the style will automatically switch to Icon, otherwise, the style will be set to Invisible. :param icon | <QIcon> || <str> || None """ icon = QIcon(icon) if icon.isNull(): self._icon = None self._style = XNodeHotspot.Style.Invisible else: self._icon = icon self._style = XNodeHotspot.Style.Icon
def make_hosts_combobox(combobox=None, default_host=None): 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 "Устанавливаем выпадающий список выбора хостингов c иконостасом" ico_host_dir = os.path.join( SCRIPT_DIR ,'icons','hosts') if not os.path.exists( ico_host_dir): ico_host_dir = os.path.join( os.sys.prefix, 'share', 'quimge', 'icons', 'hosts') if isinstance(combobox, QtGui.QComboBox): selhost = combobox else: selhost = QtGui.QComboBox() for host, obj in HOSTS.items(): ico_name = host+'.png' ico_path = os.path.join( ico_host_dir,ico_name) ico = QIcon( QPixmap( ico_path ) ) if ico.isNull(): ico = get_favicon( host, ico_path) selhost.addItem(ico, " %s"%host, QVariant([host, obj]) ) if default_host: index = selhost.findText( default_host, QtCore.Qt.MatchEndsWith ) selhost.setCurrentIndex( index if index else 1 ) return selhost
def _determineIcon(self, iconName, defaultIconName=None): """ Determines the icon identified by the given name. """ icon = None if iconName in self._loadedIcons: icon = self._loadedIcons[iconName] else: registeredIcon = self._iconHandler.getIcon(iconName) if registeredIcon is None: icon = QIcon(_ICON_RESOURCE_PREFIX + iconName + SMALL_ICONFILENAME_SUFFIX) else: icon = QIcon(registeredIcon.smallIconLocalPath) if icon.isNull() and not defaultIconName is None: icon = QIcon(_ICON_RESOURCE_PREFIX + defaultIconName + SMALL_ICONFILENAME_SUFFIX) if icon.pixmap(1, 1).isNull(): icon = None else: self._loadedIcons[iconName] = icon return icon
def createGroupItem(self, name, content = None): if not content: group = self.iface.getGroup(name) localName, icon_path = unicode(group.localName), group.icon package_count = len(self.state.groupPackages(name)) if package_count <= 0: return else: localName, icon_path = content[0], content[1] package_count = content[2] icon = QIcon(KIconLoader().loadIcon(icon_path, KIconLoader.NoGroup, 22)) if icon.isNull(): icon = self.defaultIcon text = "%s (%d)" % (localName, package_count) item = QListWidgetItem(icon, text, self) item.setToolTip(localName) item.setData(Qt.UserRole, QVariant(unicode(name))) item.setSizeHint(QSize(0, KIconLoader.SizeMedium)) self._list[name] = item
class GraphicsIconItem(QGraphicsItem): """ A graphics item displaying an :class:`QIcon`. """ def __init__(self, parent=None, icon=None, iconSize=None, **kwargs): QGraphicsItem.__init__(self, parent, **kwargs) self.setFlag(QGraphicsItem.ItemUsesExtendedStyleOption, True) if icon is None: icon = QIcon() if iconSize is None: style = QApplication.instance().style() size = style.pixelMetric(style.PM_LargeIconSize) iconSize = QSize(size, size) self.__transformationMode = Qt.SmoothTransformation self.__iconSize = QSize(iconSize) self.__icon = QIcon(icon) def setIcon(self, icon): """ Set the icon (:class:`QIcon`). """ if self.__icon != icon: self.__icon = QIcon(icon) self.update() def icon(self): """ Return the icon (:class:`QIcon`). """ return QIcon(self.__icon) def setIconSize(self, size): """ Set the icon (and this item's) size (:class:`QSize`). """ if self.__iconSize != size: self.prepareGeometryChange() self.__iconSize = QSize(size) self.update() def iconSize(self): """ Return the icon size (:class:`QSize`). """ return QSize(self.__iconSize) def setTransformationMode(self, mode): """ Set pixmap transformation mode. (`Qt.SmoothTransformation` or `Qt.FastTransformation`). """ if self.__transformationMode != mode: self.__transformationMode = mode self.update() def transformationMode(self): """ Return the pixmap transformation mode. """ return self.__transformationMode def boundingRect(self): return QRectF(0, 0, self.__iconSize.width(), self.__iconSize.height()) def paint(self, painter, option, widget=None): if not self.__icon.isNull(): if option.state & QStyle.State_Selected: mode = QIcon.Selected elif option.state & QStyle.State_Enabled: mode = QIcon.Normal elif option.state & QStyle.State_Active: mode = QIcon.Active else: mode = QIcon.Disabled transform = self.sceneTransform() if widget is not None: # 'widget' is the QGraphicsView.viewport() view = widget.parent() if isinstance(view, QGraphicsView): # Combine the scene transform with the view transform. view_transform = view.transform() transform = view_transform * view_transform lod = option.levelOfDetailFromTransform(transform) w, h = self.__iconSize.width(), self.__iconSize.height() target = QRectF(0, 0, w, h) source = QRectF(0, 0, w * lod, w * lod).toRect() # The actual size of the requested pixmap can be smaller. size = self.__icon.actualSize(source.size(), mode=mode) source.setSize(size) pixmap = self.__icon.pixmap(source.size(), mode=mode) painter.setRenderHint( QPainter.SmoothPixmapTransform, self.__transformationMode == Qt.SmoothTransformation ) painter.drawPixmap(target, pixmap, QRectF(source))
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/qgsCsvAzmDist2LatLon/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/RasterSeriesProcess/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
class GraphicsIconItem(QGraphicsItem): """ A graphics item displaying an :class:`QIcon`. """ def __init__(self, parent=None, icon=None, iconSize=None, **kwargs): QGraphicsItem.__init__(self, parent, **kwargs) self.setFlag(QGraphicsItem.ItemUsesExtendedStyleOption, True) if icon is None: icon = QIcon() if iconSize is None: style = QApplication.instance().style() size = style.pixelMetric(style.PM_LargeIconSize) iconSize = QSize(size, size) self.__transformationMode = Qt.SmoothTransformation self.__iconSize = QSize(iconSize) self.__icon = QIcon(icon) def setIcon(self, icon): """ Set the icon (:class:`QIcon`). """ if self.__icon != icon: self.__icon = QIcon(icon) self.update() def icon(self): """ Return the icon (:class:`QIcon`). """ return QIcon(self.__icon) def setIconSize(self, size): """ Set the icon (and this item's) size (:class:`QSize`). """ if self.__iconSize != size: self.prepareGeometryChange() self.__iconSize = QSize(size) self.update() def iconSize(self): """ Return the icon size (:class:`QSize`). """ return QSize(self.__iconSize) def setTransformationMode(self, mode): """ Set pixmap transformation mode. (`Qt.SmoothTransformation` or `Qt.FastTransformation`). """ if self.__transformationMode != mode: self.__transformationMode = mode self.update() def transformationMode(self): """ Return the pixmap transformation mode. """ return self.__transformationMode def boundingRect(self): return QRectF(0, 0, self.__iconSize.width(), self.__iconSize.height()) def paint(self, painter, option, widget=None): if not self.__icon.isNull(): if option.state & QStyle.State_Selected: mode = QIcon.Selected elif option.state & QStyle.State_Enabled: mode = QIcon.Normal elif option.state & QStyle.State_Active: mode = QIcon.Active else: mode = QIcon.Disabled transform = self.sceneTransform() if widget is not None: # 'widget' is the QGraphicsView.viewport() view = widget.parent() if isinstance(view, QGraphicsView): # Combine the scene transform with the view transform. view_transform = view.transform() transform = view_transform * view_transform lod = option.levelOfDetailFromTransform(transform) w, h = self.__iconSize.width(), self.__iconSize.height() target = QRectF(0, 0, w, h) source = QRectF(0, 0, w * lod, w * lod).toRect() # The actual size of the requested pixmap can be smaller. size = self.__icon.actualSize(source.size(), mode=mode) source.setSize(size) pixmap = self.__icon.pixmap(source.size(), mode=mode) painter.setRenderHint( QPainter.SmoothPixmapTransform, self.__transformationMode == Qt.SmoothTransformation) painter.drawPixmap(target, pixmap, QRectF(source))
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/ARPAP_SpatialReport/icon/icon2.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ":/plugins/maps2WinBUGS/icon.png" icon = QIcon(path) self.assertFalse(icon.isNull())
class CanvasView(QGraphicsView): """Canvas View handles the zooming. """ def __init__(self, *args): QGraphicsView.__init__(self, *args) self.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.__backgroundIcon = QIcon() self.__autoScroll = False self.__autoScrollMargin = 16 self.__autoScrollTimer = QTimer(self) self.__autoScrollTimer.timeout.connect(self.__autoScrollAdvance) def setScene(self, scene): QGraphicsView.setScene(self, scene) self._ensureSceneRect(scene) def _ensureSceneRect(self, scene): r = scene.addRect(QRectF(0, 0, 400, 400)) scene.sceneRect() scene.removeItem(r) def setAutoScrollMargin(self, margin): self.__autoScrollMargin = margin def autoScrollMargin(self): return self.__autoScrollMargin def setAutoScroll(self, enable): self.__autoScroll = enable def autoScroll(self): return self.__autoScroll def mousePressEvent(self, event): QGraphicsView.mousePressEvent(self, event) def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: if not self.__autoScrollTimer.isActive() and \ self.__shouldAutoScroll(event.pos()): self.__startAutoScroll() QGraphicsView.mouseMoveEvent(self, event) def mouseReleaseEvent(self, event): if event.button() & Qt.LeftButton: self.__stopAutoScroll() return QGraphicsView.mouseReleaseEvent(self, event) def __shouldAutoScroll(self, pos): if self.__autoScroll: margin = self.__autoScrollMargin viewrect = self.contentsRect() rect = viewrect.adjusted(margin, margin, -margin, -margin) # only do auto scroll when on the viewport's margins return not rect.contains(pos) and viewrect.contains(pos) else: return False def __startAutoScroll(self): self.__autoScrollTimer.start(10) log.debug("Auto scroll timer started") def __stopAutoScroll(self): if self.__autoScrollTimer.isActive(): self.__autoScrollTimer.stop() log.debug("Auto scroll timer stopped") def __autoScrollAdvance(self): """Advance the auto scroll """ pos = QCursor.pos() pos = self.mapFromGlobal(pos) margin = self.__autoScrollMargin vvalue = self.verticalScrollBar().value() hvalue = self.horizontalScrollBar().value() vrect = QRect(0, 0, self.width(), self.height()) # What should be the speed advance = 10 # We only do auto scroll if the mouse is inside the view. if vrect.contains(pos): if pos.x() < vrect.left() + margin: self.horizontalScrollBar().setValue(hvalue - advance) if pos.y() < vrect.top() + margin: self.verticalScrollBar().setValue(vvalue - advance) if pos.x() > vrect.right() - margin: self.horizontalScrollBar().setValue(hvalue + advance) if pos.y() > vrect.bottom() - margin: self.verticalScrollBar().setValue(vvalue + advance) if self.verticalScrollBar().value() == vvalue and \ self.horizontalScrollBar().value() == hvalue: self.__stopAutoScroll() else: self.__stopAutoScroll() log.debug("Auto scroll advance") def setBackgroundIcon(self, icon): if not isinstance(icon, QIcon): raise TypeError("A QIcon expected.") if self.__backgroundIcon != icon: self.__backgroundIcon = icon self.viewport().update() def backgroundIcon(self): return QIcon(self.__backgroundIcon) def drawBackground(self, painter, rect): QGraphicsView.drawBackground(self, painter, rect) if not self.__backgroundIcon.isNull(): painter.setClipRect(rect) vrect = QRect(QPoint(0, 0), self.viewport().size()) vrect = self.mapToScene(vrect).boundingRect() pm = self.__backgroundIcon.pixmap(vrect.size().toSize().boundedTo( QSize(200, 200))) pmrect = QRect(QPoint(0, 0), pm.size()) pmrect.moveCenter(vrect.center().toPoint()) if rect.toRect().intersects(pmrect): painter.drawPixmap(pmrect, pm)
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/InterfaceExperiment/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/ComplexGmlInfo/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/geobricks_qgis_plugin_faostat/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/GeogigPackageCreator/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/RadiationReconnaissanceResults/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
class Dialog(QDialog): """A Dialog with basic layout features: a main widget, an icon or pixmap, a separator, buttons (provided by a QDialogButtonBox) """ def __init__(self, parent=None, message="", title="", icon=None, iconSize=QSize(64, 64), pixmap=None, separator=True, buttonOrientation=Qt.Horizontal, buttons=('ok', 'cancel'), help=None, **kwargs): """Initializes the dialog. parent = a parent widget or None. The following keyword arguments are recognized: - message: the text to display in the message label - title: the window title - icon or pixmap: shown in the left area - iconSize: size of the icon in the left (QSize, default: 64x64) - separator: draw a separator line or not (default: True) - buttonOrientation: Qt.Horizontal (default) or Qt.Vertical - buttons: which buttons to use (default: Ok, Cancel) - help: function to call when a help button is clicked. Other keyword arguments are passed to QDialog. """ super(Dialog, self).__init__(parent, **kwargs) self._icon = QIcon() self._separatorWidget = Separator() self._mainWidget = QWidget() self._pixmap = QPixmap() self._pixmapLabel = QLabel(self) self._messageLabel = QLabel(self) self._buttonBox = b = QDialogButtonBox(self) b.accepted.connect(self.accept) b.rejected.connect(self.reject) layout = QGridLayout() layout.setSpacing(10) self.setLayout(layout) # handle keyword args self._buttonOrientation = buttonOrientation self._iconSize = iconSize self._separator = separator if title: self.setWindowTitle(title) self.setMessage(message) if icon: self.setIcon(icon) elif pixmap: self.setPixmap(pixmap) b.helpRequested.connect(help or self.helpRequest) self.setStandardButtons(buttons) self.reLayout() def helpRequest(self): """Called when a help button is clicked.""" pass def setButtonOrientation(self, orientation): """Sets the button orientation. Qt.Horizontal (default) puts the buttons at the bottom of the dialog in a horizonzal row, Qt.Vertical puts the buttons at the right in a vertical column. """ if orientation != self._buttonOrientation: self._buttonOrientation = orientation self._buttonBox.setOrientation(orientation) self.reLayout() def buttonOrientation(self): """Returns the button orientation.""" return self._buttonOrientation def setIcon(self, icon): """Sets the icon to display in the left area. May be: - None or QIcon() - one of 'info', 'warning', 'critical', 'question' - a QStyle.StandardPixmap - a QIcon. """ if icon in standardicons: icon = standardicons[icon] if isinstance(icon, QStyle.StandardPixmap): icon = self.style().standardIcon(icon) if icon is None: icon = QIcon() self._icon = icon self.setPixmap(icon.pixmap(self._iconSize)) def icon(self): """Returns the currently set icon as a QIcon.""" return self._icon def setIconSize(self, size): """Sets the icon size (QSize or int).""" if isinstance(size, int): size = QSize(size, size) changed = size != self._iconSize self._iconSize = size if changed and not self._icon.isNull(): self.setPixmap(self._icon.pixmap(size)) def iconSize(self): """Returns the icon size (QSize).""" return self._iconSize def setPixmap(self, pixmap): """Sets the pixmap to display in the left area.""" changed = self._pixmap.isNull() != pixmap.isNull() self._pixmap = pixmap self._pixmapLabel.setPixmap(pixmap) if not pixmap.isNull(): self._pixmapLabel.setFixedSize(pixmap.size()) if changed: self.reLayout() def pixmap(self): """Returns the currently set pixmap.""" return self._pixmap def setMessage(self, text): """Sets the main text in the dialog.""" self._messageLabel.setText(text) def message(self): """Returns the main text.""" return self._messageLabel.text() def messageLabel(self): """Returns the QLabel displaying the message text.""" return self._messageLabel def buttonBox(self): """Returns our QDialogButtonBox instance.""" return self._buttonBox def setStandardButtons(self, buttons): """Convenience method to set standard buttons in the button box. Accepts a sequence of string names from the standardbuttons constant, or a QDialogButtonBox.StandardButtons value. """ if isinstance(buttons, (set, tuple, list)): buttons = functools.reduce(operator.or_, map(standardbuttons.get, buttons), QDialogButtonBox.StandardButtons()) self._buttonBox.setStandardButtons(buttons) def button(self, button): """Returns the given button. May be a QDialogButtonBox.StandardButton or a key from standardbuttons. """ if button in standardbuttons: button = standardbuttons[button] return self._buttonBox.button(button) def setSeparator(self, enabled): """Sets whether to show a line between contents and buttons.""" changed = self._separator != enabled self._separator = enabled if changed: self.reLayout() def hasSeparator(self): """Returns whether a separator line is shown.""" return self._separator def setMainWidget(self, widget): """Sets the specified widget as our main widget.""" old = self._mainWidget if old: old.setParent(None) self._mainWidget = widget self.reLayout() def mainWidget(self): """Returns the current main widget (an empty QWidget by default).""" return self._mainWidget def reLayout(self): """(Internal) Lays out all items in this dialog.""" layout = self.layout() while layout.takeAt(0): pass if not self._pixmap.isNull(): col = 1 layout.addWidget(self._pixmapLabel, 0, 0, 2, 1) else: layout.setColumnStretch(1, 0) col = 0 layout.setColumnStretch(col, 1) self._pixmapLabel.setVisible(not self._pixmap.isNull()) layout.addWidget(self._messageLabel, 0, col) layout.addWidget(self._mainWidget, 1, col) if self._buttonOrientation == Qt.Horizontal: if self._separator: layout.addWidget(self._separatorWidget, 2, 0, 1, col + 1) layout.addWidget(self._buttonBox, 3, 0, 1, col + 1) else: if self._separator: layout.addWidget(self._separatorWidget, 0, col + 1, 2, 1) layout.addWidget(self._buttonBox, 0, col + 2, 2, 1) self._separatorWidget.setVisible(self._separator)
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/RepairLinesConncetions/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/DeactivateActiveLabels/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/RclSimplification/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/ActivitatsEconomiquesAdmin/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/ContrastHomogenizer/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/AdminZoneKorea/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/Perigosidade_PMDFCI/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Read icon from resources (test_resources.test_icon_png).""" path = ':/plugins/qgis2web_class/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/MakeOSMRoutableNetwork/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ":/plugins/rcmrdTSerieries/icon.png" icon = QIcon(path) self.assertFalse(icon.isNull())
class MessageWidget(QWidget): """ A widget displaying a simple message to the user. This is an alternative to a full QMessageBox intended for inline modeless messages. [[icon] {Message text} (Ok) (Cancel)] """ #: Emitted when a button with the AcceptRole is clicked accepted = Signal() #: Emitted when a button with the RejectRole is clicked rejected = Signal() #: Emitted when a button with the HelpRole is clicked helpRequested = Signal() #: Emitted when a button is clicked clicked = Signal(QAbstractButton) class StandardButton(enum.IntEnum): NoButton, Ok, Close, Help = 0x0, 0x1, 0x2, 0x4 NoButton, Ok, Close, Help = list(StandardButton) class ButtonRole(enum.IntEnum): InvalidRole, AcceptRole, RejectRole, HelpRole = 0, 1, 2, 3 InvalidRole, AcceptRole, RejectRole, HelpRole = list(ButtonRole) _Button = namedtuple("_Button", ["button", "role", "stdbutton"]) def __init__(self, parent=None, icon=QIcon(), text="", wordWrap=False, textFormat=Qt.AutoText, standardButtons=NoButton, **kwargs): super().__init__(parent, **kwargs) self.__text = text self.__icon = QIcon() self.__wordWrap = wordWrap self.__standardButtons = MessageWidget.NoButton self.__buttons = [] layout = QHBoxLayout() layout.setContentsMargins(8, 0, 8, 0) self.__iconlabel = QLabel(objectName="icon-label") self.__iconlabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.__textlabel = QLabel(objectName="text-label", text=text, wordWrap=wordWrap, textFormat=textFormat) if sys.platform == "darwin": self.__textlabel.setAttribute(Qt.WA_MacSmallSize) layout.addWidget(self.__iconlabel) layout.addWidget(self.__textlabel) self.setLayout(layout) self.setIcon(icon) self.setStandardButtons(standardButtons) def setText(self, text): """ Set the current message text. :type message: str """ if self.__text != text: self.__text = text self.__textlabel.setText(text) def text(self): """ Return the current message text. :rtype: str """ return self.__text def setIcon(self, icon): """ Set the message icon. :type icon: QIcon | QPixmap | QString | QStyle.StandardPixmap """ if isinstance(icon, QStyle.StandardPixmap): icon = self.style().standardIcon(icon) else: icon = QIcon(icon) if self.__icon != icon: self.__icon = QIcon(icon) if not self.__icon.isNull(): size = self.style().pixelMetric( QStyle.PM_SmallIconSize, None, self) pm = self.__icon.pixmap(QSize(size, size)) else: pm = QPixmap() self.__iconlabel.setPixmap(pm) self.__iconlabel.setVisible(not pm.isNull()) def icon(self): """ Return the current icon. :rtype: QIcon """ return QIcon(self.__icon) def setWordWrap(self, wordWrap): """ Set the message text wrap property :type wordWrap: bool """ if self.__wordWrap != wordWrap: self.__wordWrap = wordWrap self.__textlabel.setWordWrap(wordWrap) def wordWrap(self): """ Return the message text wrap property. :rtype: bool """ return self.__wordWrap def setTextFormat(self, textFormat): """ Set message text format :type textFormat: Qt.TextFormat """ self.__textlabel.setTextFormat(textFormat) def textFormat(self): """ Return the message text format. :rtype: Qt.TextFormat """ return self.__textlabel.textFormat() def changeEvent(self, event): # reimplemented if event.type() == 177: # QEvent.MacSizeChange: ... super().changeEvent(event) def setStandardButtons(self, buttons): for button in MessageWidget.StandardButton: existing = self.button(button) if button & buttons and existing is None: self.addButton(button) elif existing is not None: self.removeButton(existing) def standardButtons(self): return functools.reduce( operator.ior, (slot.stdbutton for slot in self.__buttons if slot.stdbutton is not None), MessageWidget.NoButton) def addButton(self, button, *rolearg): """ addButton(QAbstractButton, ButtonRole) addButton(str, ButtonRole) addButton(StandardButton) Add and return a button """ stdbutton = None if isinstance(button, QAbstractButton): if len(rolearg) != 1: raise TypeError("Wrong number of arguments for " "addButton(QAbstractButton, role)") role = rolearg[0] elif isinstance(button, MessageWidget.StandardButton): if len(rolearg) != 0: raise TypeError("Wrong number of arguments for " "addButton(StandardButton)") stdbutton = button if button == MessageWidget.Ok: role = MessageWidget.AcceptRole button = QPushButton("Ok", default=False, autoDefault=False) elif button == MessageWidget.Close: role = MessageWidget.RejectRole # button = QPushButton( # default=False, autoDefault=False, flat=True, # icon=QIcon(self.style().standardIcon( # QStyle.SP_TitleBarCloseButton))) button = SimpleButton( icon=QIcon(self.style().standardIcon( QStyle.SP_TitleBarCloseButton))) elif button == MessageWidget.Help: role = MessageWidget.HelpRole button = QPushButton("Help", default=False, autoDefault=False) elif isinstance(button, str): if len(rolearg) != 1: raise TypeError("Wrong number of arguments for " "addButton(str, ButtonRole)") role = rolearg[0] button = QPushButton(button, default=False, autoDefault=False) if sys.platform == "darwin": button.setAttribute(Qt.WA_MacSmallSize) self.__buttons.append(MessageWidget._Button(button, role, stdbutton)) button.clicked.connect(self.__button_clicked) self.__relayout() return button def removeButton(self, button): """ Remove a `button`. :type button: QAbstractButton """ slot = [s for s in self.__buttons if s.button is button] if slot: slot = slot[0] self.__buttons.remove(slot) self.layout().removeWidget(slot.button) slot.button.setParent(None) def buttonRole(self, button): """ Return the ButtonRole for button :type button: QAbsstractButton """ for slot in self.__buttons: if slot.button is button: return slot.role else: return MessageWidget.InvalidRole def button(self, standardButton): """ Return the button for the StandardButton. :type standardButton: StandardButton """ for slot in self.__buttons: if slot.stdbutton == standardButton: return slot.button else: return None def __button_clicked(self): button = self.sender() role = self.buttonRole(button) self.clicked.emit(button) if role == MessageWidget.AcceptRole: self.accepted.emit() self.close() elif role == MessageWidget.RejectRole: self.rejected.emit() self.close() elif role == MessageWidget.HelpRole: self.helpRequested.emit() def __relayout(self): for slot in self.__buttons: self.layout().removeWidget(slot.button) order = { MessageOverlayWidget.HelpRole: 0, MessageOverlayWidget.AcceptRole: 2, MessageOverlayWidget.RejectRole: 3, } orderd = sorted(self.__buttons, key=lambda slot: order.get(slot.role, -1)) prev = self.__textlabel for slot in orderd: self.layout().addWidget(slot.button) QWidget.setTabOrder(prev, slot.button)
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/LizardDownloader/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/GeobricksQgisPluginWorldBank/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/VectorSelectByPoint/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/populateauthsystem/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/FindTransitAccessibleTrailheads/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/AzimuthMeasurement/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/PolygonBySegmentBuffer/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/GeoCoder_AdresseVask/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/drfLayerSourceEditor/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/GroundRadiationMonitoring/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
class Dialog(QDialog): """A Dialog with basic layout features: a main widget, an icon or pixmap, a separator, buttons (provided by a QDialogButtonBox) """ def __init__(self, parent = None, message = "", title = "", icon = None, iconSize = QSize(64, 64), pixmap = None, separator = True, buttonOrientation = Qt.Horizontal, buttons = ('ok', 'cancel'), help = None, **kwargs): """Initializes the dialog. parent = a parent widget or None. The following keyword arguments are recognized: - message: the text to display in the message label - title: the window title - icon or pixmap: shown in the left area - iconSize: size of the icon in the left (QSize, default: 64x64) - separator: draw a separator line or not (default: True) - buttonOrientation: Qt.Horizontal (default) or Qt.Vertical - buttons: which buttons to use (default: Ok, Cancel) - help: function to call when a help button is clicked. Other keyword arguments are passed to QDialog. """ super(Dialog, self).__init__(parent, **kwargs) self._icon = QIcon() self._separatorWidget = Separator() self._mainWidget = QWidget() self._pixmap = QPixmap() self._pixmapLabel = QLabel(self) self._messageLabel = QLabel(self) self._buttonBox = b = QDialogButtonBox(self) b.accepted.connect(self.accept) b.rejected.connect(self.reject) layout = QGridLayout() layout.setSpacing(10) self.setLayout(layout) # handle keyword args self._buttonOrientation = buttonOrientation self._iconSize = iconSize self._separator = separator if title: self.setWindowTitle(title) self.setMessage(message) if icon: self.setIcon(icon) elif pixmap: self.setPixmap(pixmap) b.helpRequested.connect(help or self.helpRequest) self.setStandardButtons(buttons) self.reLayout() def helpRequest(self): """Called when a help button is clicked.""" pass def setButtonOrientation(self, orientation): """Sets the button orientation. Qt.Horizontal (default) puts the buttons at the bottom of the dialog in a horizontal row, Qt.Vertical puts the buttons at the right in a vertical column. """ if orientation != self._buttonOrientation: self._buttonOrientation = orientation self._buttonBox.setOrientation(orientation) self.reLayout() def buttonOrientation(self): """Returns the button orientation.""" return self._buttonOrientation def setIcon(self, icon): """Sets the icon to display in the left area. May be: - None or QIcon() - one of 'info', 'warning', 'critical', 'question' - a QStyle.StandardPixmap - a QIcon. """ if icon in standardicons: icon = standardicons[icon] if isinstance(icon, QStyle.StandardPixmap): icon = self.style().standardIcon(icon) if icon is None: icon = QIcon() self._icon = icon self.setPixmap(icon.pixmap(self._iconSize)) def icon(self): """Returns the currently set icon as a QIcon.""" return self._icon def setIconSize(self, size): """Sets the icon size (QSize or int).""" if isinstance(size, int): size = QSize(size, size) changed = size != self._iconSize self._iconSize = size if changed and not self._icon.isNull(): self.setPixmap(self._icon.pixmap(size)) def iconSize(self): """Returns the icon size (QSize).""" return self._iconSize def setPixmap(self, pixmap): """Sets the pixmap to display in the left area.""" changed = self._pixmap.isNull() != pixmap.isNull() self._pixmap = pixmap self._pixmapLabel.setPixmap(pixmap) if not pixmap.isNull(): self._pixmapLabel.setFixedSize(pixmap.size()) if changed: self.reLayout() def pixmap(self): """Returns the currently set pixmap.""" return self._pixmap def setMessage(self, text): """Sets the main text in the dialog.""" self._messageLabel.setText(text) def message(self): """Returns the main text.""" return self._messageLabel.text() def messageLabel(self): """Returns the QLabel displaying the message text.""" return self._messageLabel def buttonBox(self): """Returns our QDialogButtonBox instance.""" return self._buttonBox def setStandardButtons(self, buttons): """Convenience method to set standard buttons in the button box. Accepts a sequence of string names from the standardbuttons constant, or a QDialogButtonBox.StandardButtons value. """ if isinstance(buttons, (set, tuple, list)): buttons = functools.reduce(operator.or_, map(standardbuttons.get, buttons), QDialogButtonBox.StandardButtons()) self._buttonBox.setStandardButtons(buttons) def button(self, button): """Returns the given button. May be a QDialogButtonBox.StandardButton or a key from standardbuttons. """ if button in standardbuttons: button = standardbuttons[button] return self._buttonBox.button(button) def setSeparator(self, enabled): """Sets whether to show a line between contents and buttons.""" changed = self._separator != enabled self._separator = enabled if changed: self.reLayout() def hasSeparator(self): """Returns whether a separator line is shown.""" return self._separator def setMainWidget(self, widget): """Sets the specified widget as our main widget.""" old = self._mainWidget if old: old.setParent(None) self._mainWidget = widget self.reLayout() def mainWidget(self): """Returns the current main widget (an empty QWidget by default).""" return self._mainWidget def reLayout(self): """(Internal) Lays out all items in this dialog.""" layout = self.layout() while layout.takeAt(0): pass if not self._pixmap.isNull(): col = 1 layout.addWidget(self._pixmapLabel, 0, 0, 2, 1) else: layout.setColumnStretch(1, 0) col = 0 layout.setColumnStretch(col, 1) self._pixmapLabel.setVisible(not self._pixmap.isNull()) layout.addWidget(self._messageLabel, 0, col) layout.addWidget(self._mainWidget, 1, col) if self._buttonOrientation == Qt.Horizontal: if self._separator: layout.addWidget(self._separatorWidget, 2, 0, 1, col+1) layout.addWidget(self._buttonBox, 3, 0, 1, col+1) else: if self._separator: layout.addWidget(self._separatorWidget, 0, col+1, 2, 1) layout.addWidget(self._buttonBox, 0, col+2, 2, 1) self._separatorWidget.setVisible(self._separator)
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/SatelliteImageryManager/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/wfsOutputExtension/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/UkrainianCadastralMap/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/FTM/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/SurafaceTriangulation/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/RGBvalue/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())
def test_icon_png(self): """Test we can click OK.""" path = ':/plugins/ProfileFromPoints/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull())