##// END OF EJS Templates
Add context manager for temporary directories from Python 3.2...
Add context manager for temporary directories from Python 3.2 This is very useful in tests, and after writing my own version I found out that python 3.2 has now a basically identical implementation to mine, so I copied that instead. We can remove our copy once we're not supporting python 2.x anymore.

File last commit:

r2765:1f32be1b
r3182:ae65e73c
Show More
svg.py
89 lines | 2.4 KiB | text/x-python | PythonLexer
""" Defines utility functions for working with SVG documents in Qt.
"""
# System library imports.
from PyQt4 import QtCore, QtGui, QtSvg
def save_svg(string, parent=None):
""" Prompts the user to save an SVG document to disk.
Parameters:
-----------
string : str
A Python string or QString containing a SVG document.
parent : QWidget, optional
The parent to use for the file dialog.
Returns:
--------
The name of the file to which the document was saved, or None if the save
was cancelled.
"""
dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix('svg')
dialog.setNameFilter('SVG document (*.svg)')
if dialog.exec_():
filename = dialog.selectedFiles()[0]
f = open(filename, 'w')
try:
f.write(string)
finally:
f.close()
return filename
return None
def svg_to_clipboard(string):
""" Copy a SVG document to the clipboard.
Parameters:
-----------
string : str
A Python string or QString containing a SVG document.
"""
if isinstance(string, basestring):
bytes = QtCore.QByteArray(string)
else:
bytes = string.toAscii()
mime_data = QtCore.QMimeData()
mime_data.setData('image/svg+xml', bytes)
QtGui.QApplication.clipboard().setMimeData(mime_data)
def svg_to_image(string, size=None):
""" Convert a SVG document to a QImage.
Parameters:
-----------
string : str
A Python string or QString containing a SVG document.
size : QSize, optional
The size of the image that is produced. If not specified, the SVG
document's default size is used.
Raises:
-------
ValueError
If an invalid SVG string is provided.
Returns:
--------
A QImage of format QImage.Format_ARGB32.
"""
if isinstance(string, basestring):
bytes = QtCore.QByteArray.fromRawData(string) # shallow copy
else:
bytes = string.toAscii()
renderer = QtSvg.QSvgRenderer(bytes)
if not renderer.isValid():
raise ValueError('Invalid SVG data.')
if size is None:
size = renderer.defaultSize()
image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
painter = QtGui.QPainter(image)
renderer.render(painter)
return image