本文整理匯總了Python中qtpy.QtGui.QPixmap類的典型用法代碼示例。如果您正苦於以下問題:Python QPixmap類的具體用法?Python QPixmap怎麽用?Python QPixmap使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了QPixmap類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: set_color
def set_color(self, color):
if color != self._color:
self._color = color
self.colorChanged.emit(self._color)
pixmap = QPixmap(self.iconSize())
pixmap.fill(color)
self.setIcon(QIcon(pixmap))
示例2: test_zoom_figure_viewer
def test_zoom_figure_viewer(figbrowser, tmpdir, fmt):
"""
Test zooming in and out the figure diplayed in the figure viewer.
"""
fig = add_figures_to_browser(figbrowser, 1, tmpdir, fmt)[0]
figcanvas = figbrowser.figviewer.figcanvas
# Calculate original figure size in pixels.
qpix = QPixmap()
qpix.loadFromData(fig, fmt.upper())
fwidth, fheight = qpix.width(), qpix.height()
assert figbrowser.zoom_disp.value() == 100
assert figcanvas.width() == fwidth
assert figcanvas.height() == fheight
# Zoom in and out the figure in the figure viewer.
scaling_factor = 0
scaling_step = figbrowser.figviewer._scalestep
for zoom_step in [1, 1, -1, -1, -1]:
if zoom_step == 1:
figbrowser.zoom_in()
elif zoom_step == -1:
figbrowser.zoom_out()
scaling_factor += zoom_step
scale = scaling_step**scaling_factor
assert figbrowser.zoom_disp.value() == np.floor(scale * 100)
assert figcanvas.width() == np.floor(fwidth * scale)
assert figcanvas.height() == np.floor(fheight * scale)
示例3: copy_figure
def copy_figure(self):
"""Copy figure to clipboard."""
if self.fmt in ['image/png', 'image/jpeg']:
qpixmap = QPixmap()
qpixmap.loadFromData(self.fig, self.fmt.upper())
QApplication.clipboard().setImage(qpixmap.toImage())
elif self.fmt == 'image/svg+xml':
svg_to_clipboard(self.fig)
else:
return
self.blink_figure()
示例4: test_save_all_figures
def test_save_all_figures(figbrowser, tmpdir, mocker, fmt):
"""
Test saving all figures contained in the thumbnail scrollbar in batch
into a single directory.
"""
figs = add_figures_to_browser(figbrowser, 3, tmpdir, fmt)
# Save all figures, but cancel the dialog to get a directory.
mocker.patch(
'spyder.plugins.plots.widgets.figurebrowser.getexistingdirectory',
return_value=None)
fignames = figbrowser.save_all_figures()
assert fignames is None
# Save all figures.
mocker.patch(
'spyder.plugins.plots.widgets.figurebrowser.getexistingdirectory',
return_value=to_text_string(tmpdir.mkdir('all_saved_figures')))
fignames = figbrowser.save_all_figures()
assert len(fignames) == len(figs)
for fig, figname in zip(figs, fignames):
expected_qpix = QPixmap()
expected_qpix.loadFromData(fig, fmt.upper())
saved_qpix = QPixmap()
saved_qpix.load(figname)
assert osp.exists(figname)
assert expected_qpix.toImage() == saved_qpix.toImage()
示例5: imageFiles
def imageFiles(self, new_files):
"""
JSON-formatted dictionary keyed on states (integers), with filenames
of the image file to display for the state.
Parameters
----------
new_files : str
"""
self._state_images_string = str(new_files)
try:
new_file_dict = json.loads(self._state_images_string)
except Exception:
self._state_images = {}
return
self._sizeHint = QSize(0, 0)
for (state, filename) in new_file_dict.items():
if is_pydm_app():
try:
file_path = self.app.get_path(filename)
except Exception as e:
logger.exception("Couldn't get file with path %s", filename)
file_path = filename
else:
file_path = filename
# First, lets try SVG. We have to try SVG first, otherwise
# QPixmap will happily load the SVG and turn it into a raster image.
# Really annoying: We have to try to load the file as SVG,
# and we expect it will fail often (because many images aren't SVG).
# Qt prints a warning message to stdout any time SVG loading fails.
# So we have to temporarily silence Qt warning messages here.
qInstallMessageHandler(self.qt_message_handler)
svg = QSvgRenderer()
svg.repaintNeeded.connect(self.update)
if svg.load(file_path):
self._state_images[int(state)] = (filename, svg)
self._sizeHint = self._sizeHint.expandedTo(svg.defaultSize())
qInstallMessageHandler(None)
continue
qInstallMessageHandler(None)
# SVG didn't work, lets try QPixmap
image = QPixmap(file_path)
if not image.isNull():
self._state_images[int(state)] = (filename, image)
self._sizeHint = self._sizeHint.expandedTo(image.size())
continue
# If we get this far, the file specified could not be loaded at all.
logger.error("Could not load image: {}".format(filename))
self._state_images[int(state)] = (filename, None)
示例6: _set_pixmap_from_array
def _set_pixmap_from_array(self, arr):
bpl = arr.strides[0]
is_rgb = len(arr.shape) == 3
if is_rgb and arr.dtype == np.uint8:
format = QImage.Format_RGB32
image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format)
elif not is_rgb and arr.dtype == np.uint8:
# TODO: Somehow need to make sure data is ordered as I'm assuming
format = QImage.Format_Indexed8
image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format)
self._saved_img = arr
elif not is_rgb and arr.dtype == np.uint16:
if not self._cmax:
self._cmax = arr.max() # Set cmax once from first image
arr = scipy.misc.bytescale(arr, self._cmin, self._cmax)
format = QImage.Format_Indexed8
w, h = self.camera.width, self.camera.height
image = QImage(arr.data, w, h, w, format)
self._saved_img = arr # Save a reference to keep Qt from crashing
else:
raise Exception("Unsupported color mode")
self.setPixmap(QPixmap.fromImage(image))
pixmap_size = self.pixmap().size()
if pixmap_size != self.size():
self.setMinimumSize(self.pixmap().size())
示例7: __init__
def __init__(self, parent=None, icon=True):
super(SearchLineEdit, self).__init__(parent)
self.setTextMargins(1, 0, 20, 0)
if icon:
self.setTextMargins(18, 0, 20, 0)
self._label = QLabel(self)
self._pixmap_icon = QPixmap(get_image_path('conda_search.png'))
self._label.setPixmap(self._pixmap_icon)
self._label.setStyleSheet('''border: 0px; padding-bottom: 0px;
padding-left: 2px;''')
self._pixmap = QPixmap(get_image_path('conda_del.png'))
self.button_clear = QToolButton(self)
self.button_clear.setIcon(QIcon(self._pixmap))
self.button_clear.setIconSize(QSize(18, 18))
self.button_clear.setCursor(Qt.ArrowCursor)
self.button_clear.setStyleSheet("""QToolButton
{background: transparent;
padding-right: 2px; border: none; margin:0px; }""")
self.button_clear.setVisible(False)
# Layout
self._layout = QHBoxLayout(self)
self._layout.addWidget(self.button_clear, 0, Qt.AlignRight)
self._layout.setSpacing(0)
self._layout.setContentsMargins(0, 2, 2, 0)
# Signals and slots
self.button_clear.clicked.connect(self.clear_text)
self.textChanged.connect(self._toggle_visibility)
self.textEdited.connect(self._toggle_visibility)
示例8: __init__
def __init__(self, tileSource, parent=None):
"""Constructor.
Args:
tileSource(MapTileSource): Source for loading the tiles.
parent(QObject): Parent object, default `None`
"""
QGraphicsScene.__init__(self, parent=parent)
self._zoom = 15
self._tileSource = tileSource
self._tileSource.setParent(self)
self._tileSource.tileReceived.connect(self.setTilePixmap)
tdim = self._tileSource.tileSize()
self._emptyTile = QPixmap(tdim, tdim)
self._emptyTile.fill(Qt.lightGray)
self._tilesRect = QRect()
self._tilePixmaps = {}
self._tileInDownload = list()
self.setSceneRect(0.0, 0.0, 400, 300)
self.sceneRectChanged.connect(self.onSceneRectChanged)
示例9: set_data
def set_data(self, title, content, current, image, run, frames=None,
step=None):
""" """
self.label_title.setText(title)
self.combo_title.clear()
self.combo_title.addItems(frames)
self.combo_title.setCurrentIndex(step)
# min_content_len = max([len(f) for f in frames])
# self.combo_title.setMinimumContentsLength(min_content_len)
# Fix and try to see how it looks with a combo box
self.label_current.setText(current)
self.button_current.setText(current)
self.label_content.setText(content)
self.image = image
if image is None:
self.label_image.setFixedHeight(1)
self.label_image.setFixedWidth(1)
else:
extension = image.split('.')[-1]
self.image = QPixmap(get_image_path(image), extension)
self.label_image.setPixmap(self.image)
self.label_image.setFixedSize(self.image.size())
if run is None:
self.button_run.setVisible(False)
else:
self.button_run.setDisabled(False)
self.button_run.setVisible(True)
# Refresh layout
self.layout().activate()
示例10: load_figure
def load_figure(self, fig, fmt):
"""
Load the figure from a png, jpg, or svg image, convert it in
a QPixmap, and force a repaint of the widget.
"""
self.fig = fig
self.fmt = fmt
if fmt in ['image/png', 'image/jpeg']:
self._qpix_orig = QPixmap()
self._qpix_orig.loadFromData(fig, fmt.upper())
elif fmt == 'image/svg+xml':
self._qpix_orig = QPixmap(svg_to_image(fig))
self._qpix_buffer = [self._qpix_orig]
self.fwidth = self._qpix_orig.width()
self.fheight = self._qpix_orig.height()
示例11: SearchLineEdit
class SearchLineEdit(QLineEdit):
"""Line edit search widget with icon and remove all button"""
def __init__(self, parent=None, icon=True):
super(SearchLineEdit, self).__init__(parent)
self.setTextMargins(1, 0, 20, 0)
if icon:
self.setTextMargins(18, 0, 20, 0)
self._label = QLabel(self)
self._pixmap_icon = QPixmap(get_image_path('conda_search.png'))
self._label.setPixmap(self._pixmap_icon)
self._label.setStyleSheet('''border: 0px; padding-bottom: 0px;
padding-left: 2px;''')
self._pixmap = QPixmap(get_image_path('conda_del.png'))
self.button_clear = QToolButton(self)
self.button_clear.setIcon(QIcon(self._pixmap))
self.button_clear.setIconSize(QSize(18, 18))
self.button_clear.setCursor(Qt.ArrowCursor)
self.button_clear.setStyleSheet("""QToolButton
{background: transparent;
padding-right: 2px; border: none; margin:0px; }""")
self.button_clear.setVisible(False)
# Layout
self._layout = QHBoxLayout(self)
self._layout.addWidget(self.button_clear, 0, Qt.AlignRight)
self._layout.setSpacing(0)
self._layout.setContentsMargins(0, 2, 2, 0)
# Signals and slots
self.button_clear.clicked.connect(self.clear_text)
self.textChanged.connect(self._toggle_visibility)
self.textEdited.connect(self._toggle_visibility)
def _toggle_visibility(self):
""" """
if len(self.text()) == 0:
self.button_clear.setVisible(False)
else:
self.button_clear.setVisible(True)
def sizeHint(self):
return QSize(200, self._pixmap_icon.height())
# Public api
# ----------
def clear_text(self):
""" """
self.setText('')
self.setFocus()
示例12: test_save_figure_to_file
def test_save_figure_to_file(figbrowser, tmpdir, mocker, fmt, fext):
"""
Test saving png and svg figures to file with the figure browser.
"""
fig = add_figures_to_browser(figbrowser, 1, tmpdir, fmt)[0]
expected_qpix = QPixmap()
expected_qpix.loadFromData(fig, fmt.upper())
# Save the figure to disk with the figure browser.
saved_figname = osp.join(to_text_string(tmpdir), 'spyfig' + fext)
mocker.patch('spyder.plugins.plots.widgets.figurebrowser.getsavefilename',
return_value=(saved_figname, fext))
figbrowser.save_figure()
saved_qpix = QPixmap()
saved_qpix.load(saved_figname)
assert osp.exists(saved_figname)
assert expected_qpix.toImage() == saved_qpix.toImage()
示例13: test_save_thumbnails
def test_save_thumbnails(figbrowser, tmpdir, qtbot, mocker, fmt):
"""
Test saving figures by clicking on the thumbnail icon.
"""
figs = add_figures_to_browser(figbrowser, 3, tmpdir, fmt)
fext = '.svg' if fmt == 'image/svg+xml' else '.png'
# Save the second thumbnail of the scrollbar.
figname = osp.join(to_text_string(tmpdir), 'figname' + fext)
mocker.patch('spyder.plugins.plots.widgets.figurebrowser.getsavefilename',
return_value=(figname, fext))
qtbot.mouseClick(
figbrowser.thumbnails_sb._thumbnails[1].savefig_btn, Qt.LeftButton)
expected_qpix = QPixmap()
expected_qpix.loadFromData(figs[1], fmt.upper())
saved_qpix = QPixmap()
saved_qpix.load(figname)
assert osp.exists(figname)
assert expected_qpix.toImage() == saved_qpix.toImage()
示例14: __init__
def __init__(self, parent, arr):
QLabel.__init__(self)
# we need to hold a reference to
# arr because QImage doesn't copy the data
# and the buffer must be alive as long
# as the image is alive.
self.arr = arr
# we also need to pass in the row-stride to
# the constructor, because we can't guarantee
# that every row of the numpy data is
# 4-byte aligned. Which Qt would require
# if we didn't pass the stride.
self.img = QImage(arr.data, arr.shape[1], arr.shape[0],
arr.strides[0], QImage.Format_RGB888)
self.pm = QPixmap.fromImage(self.img)
self.setPixmap(self.pm)
self.setAlignment(QtCore.Qt.AlignTop)
self.setMinimumSize(100, 100)
示例15: FigureCanvas
class FigureCanvas(QFrame):
"""
A basic widget on which can be painted a custom png, jpg, or svg image.
"""
def __init__(self, parent=None):
super(FigureCanvas, self).__init__(parent)
self.setLineWidth(2)
self.setMidLineWidth(1)
self.setStyleSheet("background-color: white")
self.fig = None
self.fmt = None
self.fwidth, self.fheight = 200, 200
def clear_canvas(self):
"""Clear the figure that was painted on the widget."""
self.fig = None
self.fmt = None
self._qpix_buffer = []
self.repaint()
def load_figure(self, fig, fmt):
"""
Load the figure from a png, jpg, or svg image, convert it in
a QPixmap, and force a repaint of the widget.
"""
self.fig = fig
self.fmt = fmt
if fmt in ['image/png', 'image/jpeg']:
self._qpix_orig = QPixmap()
self._qpix_orig.loadFromData(fig, fmt.upper())
elif fmt == 'image/svg+xml':
self._qpix_orig = QPixmap(svg_to_image(fig))
self._qpix_buffer = [self._qpix_orig]
self.fwidth = self._qpix_orig.width()
self.fheight = self._qpix_orig.height()
def paintEvent(self, event):
"""Qt method override to paint a custom image on the Widget."""
super(FigureCanvas, self).paintEvent(event)
# Prepare the rect on which the image is going to be painted :
fw = self.frameWidth()
rect = QRect(0 + fw, 0 + fw,
self.size().width() - 2 * fw,
self.size().height() - 2 * fw)
if self.fig is None:
return
# Check/update the qpixmap buffer :
qpix2paint = None
for qpix in self._qpix_buffer:
if qpix.size().width() == rect.width():
qpix2paint = qpix
break
else:
if self.fmt in ['image/png', 'image/jpeg']:
qpix2paint = self._qpix_orig.scaledToWidth(
rect.width(), mode=Qt.SmoothTransformation)
elif self.fmt == 'image/svg+xml':
qpix2paint = QPixmap(svg_to_image(self.fig, rect.size()))
self._qpix_buffer.append(qpix2paint)
if qpix2paint is not None:
# Paint the image on the widget :
qp = QPainter()
qp.begin(self)
qp.drawPixmap(rect, qpix2paint)
qp.end()