本文整理汇总了Python中PyQt5.QtCore.QBuffer.open方法的典型用法代码示例。如果您正苦于以下问题:Python QBuffer.open方法的具体用法?Python QBuffer.open怎么用?Python QBuffer.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QBuffer
的用法示例。
在下文中一共展示了QBuffer.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dropEvent
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def dropEvent(self, event):
mimeData = event.mimeData()
if mimeData.hasUrls():
paths = mimeData.urls()
# pick just one image
path = paths[0].toLocalFile()
fileName = os.path.basename(path)
with open(path, "rb") as imgFile:
data = imgFile.read()
ext = os.path.splitext(path)[1][1:]
# TODO: make sure we cleanup properly when replacing an image with
# another
if ext.lower() != "png":
# convert
img = QImage(path)
data = QByteArray()
buffer = QBuffer(data)
buffer.open(QIODevice.WriteOnly)
img.save(buffer, 'PNG')
# format
data = bytearray(data)
fileName = "%s.png" % os.path.splitext(fileName)[0]
imageSet = self._glyph.font.images
try:
imageSet[fileName] = data
except Exception as e:
errorReports.showCriticalException(e)
return
image = self._glyph.instantiateImage()
image.fileName = fileName
event.setAccepted(True)
else:
super().dropEvent(event)
示例2: write
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
archive = VirtualFile()
archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
#Store the g-code from the scene.
archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
gcode_textio = StringIO() #We have to convert the g-code into bytes.
PluginRegistry.getInstance().getPluginObject("GCodeWriter").write(gcode_textio, None)
gcode = archive.getStream("/3D/model.gcode")
gcode.write(gcode_textio.getvalue().encode("UTF-8"))
archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
#Store the thumbnail.
if self._snapshot:
archive.addContentType(extension = "png", mime_type = "image/png")
thumbnail = archive.getStream("/Metadata/thumbnail.png")
thumbnail_buffer = QBuffer()
thumbnail_buffer.open(QBuffer.ReadWrite)
thumbnail_image = self._snapshot
thumbnail_image.save(thumbnail_buffer, "PNG")
thumbnail.write(thumbnail_buffer.data())
archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
else:
Logger.log("d", "Thumbnail not created, cannot save it")
archive.close()
return True
示例3: __cssLinkClass
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def __cssLinkClass(self, icon, size=32):
"""
Private method to generate a link class with an icon.
@param icon icon to be included (QIcon)
@param size size of the icon to be generated (integer)
@return CSS class string (string)
"""
cssString = \
"""a.{{0}} {{{{\n"""\
""" padding-left: {0}px;\n"""\
""" background: transparent url(data:image/png;base64,{1})"""\
""" no-repeat center left;\n"""\
""" font-weight: bold;\n"""\
"""}}}}\n"""
pixmap = icon.pixmap(size, size)
imageBuffer = QBuffer()
imageBuffer.open(QIODevice.ReadWrite)
if not pixmap.save(imageBuffer, "PNG"):
# write a blank pixmap on error
pixmap = QPixmap(size, size)
pixmap.fill(Qt.transparent)
imageBuffer.buffer().clear()
pixmap.save(imageBuffer, "PNG")
return cssString.format(
size + 4,
str(imageBuffer.buffer().toBase64(), encoding="ascii"))
示例4: _addIcon
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def _addIcon(self):
filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;"
"All files (*.*)")
fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
self.tr("Open File"), self.latestDir,
filter_)
if fileName:
file_info = QFileInfo(fileName)
self.latestDir = file_info.absolutePath()
image = QImage()
if image.load(fileName):
maxWidth = 22
maxHeight = 15
if image.width() > maxWidth or image.height() > maxHeight:
scaledImage = image.scaled(maxWidth, maxHeight,
Qt.KeepAspectRatio, Qt.SmoothTransformation)
else:
scaledImage = image
ba = QByteArray()
buffer = QBuffer(ba)
buffer.open(QIODevice.WriteOnly)
scaledImage.save(buffer, 'png')
model = self.model()
index = model.index(self.selectedIndex().row(), model.fieldIndex('icon'))
model.setData(index, ba)
示例5: requestStarted
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def requestStarted(self, job):
"""Handle a request for a qute: scheme.
This method must be reimplemented by all custom URL scheme handlers.
The request is asynchronous and does not need to be handled right away.
Args:
job: QWebEngineUrlRequestJob
"""
url = job.requestUrl()
if url.scheme() in ['chrome-error', 'chrome-extension']:
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378
job.fail(QWebEngineUrlRequestJob.UrlInvalid)
return
if not self._check_initiator(job):
return
if job.requestMethod() != b'GET':
job.fail(QWebEngineUrlRequestJob.RequestDenied)
return
assert url.scheme() == 'qute'
log.misc.debug("Got request for {}".format(url.toDisplayString()))
try:
mimetype, data = qutescheme.data_for_url(url)
except qutescheme.Error as e:
errors = {
qutescheme.NotFoundError:
QWebEngineUrlRequestJob.UrlNotFound,
qutescheme.UrlInvalidError:
QWebEngineUrlRequestJob.UrlInvalid,
qutescheme.RequestDeniedError:
QWebEngineUrlRequestJob.RequestDenied,
qutescheme.SchemeOSError:
QWebEngineUrlRequestJob.UrlNotFound,
qutescheme.Error:
QWebEngineUrlRequestJob.RequestFailed,
}
exctype = type(e)
log.misc.error("{} while handling qute://* URL".format(
exctype.__name__))
job.fail(errors[exctype])
except qutescheme.Redirect as e:
qtutils.ensure_valid(e.url)
job.redirect(e.url)
else:
log.misc.debug("Returning {} data".format(mimetype))
# We can't just use the QBuffer constructor taking a QByteArray,
# because that somehow segfaults...
# https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
buf = QBuffer(parent=self)
buf.open(QIODevice.WriteOnly)
buf.write(data)
buf.seek(0)
buf.close()
job.reply(mimetype.encode('ascii'), buf)
示例6: mouseMoveEvent
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def mouseMoveEvent(self, event):
""" If the mouse moves far enough when the left mouse button is held
down, start a drag and drop operation.
"""
if not event.buttons() & Qt.LeftButton:
return
if (event.pos() - self.dragStartPosition).manhattanLength() \
< QApplication.startDragDistance():
return
if not self.hasImage:
return
drag = QDrag(self)
mimeData = QMimeData()
output = QByteArray()
outputBuffer = QBuffer(output)
outputBuffer.open(QIODevice.WriteOnly)
self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG')
outputBuffer.close()
mimeData.setData('image/png', output)
drag.setMimeData(mimeData)
drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, Qt.KeepAspectRatio))
drag.setHotSpot(QPoint(drag.pixmap().width() / 2,
drag.pixmap().height()))
drag.start()
示例7: loadFromMemory
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def loadFromMemory(self):
""" This slot function is called in the second Dialog process, when the
user presses the "Load Image from Shared Memory" button. First, it
attaches the process to the shared memory segment created by the first
Dialog process. Then it locks the segment for exclusive access, copies
the image data from the segment into a QBuffer, and streams the QBuffer
into a QImage. Then it unlocks the shared memory segment, detaches
from it, and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setPixmap(QPixmap.fromImage(image))
示例8: mimeData
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def mimeData(self, indexes):
"""
Public method to return the mime data.
@param indexes list of indexes (QModelIndexList)
@return mime data (QMimeData)
"""
from .XbelWriter import XbelWriter
data = QByteArray()
stream = QDataStream(data, QIODevice.WriteOnly)
urls = []
for index in indexes:
if index.column() != 0 or not index.isValid():
continue
encodedData = QByteArray()
buffer = QBuffer(encodedData)
buffer.open(QIODevice.ReadWrite)
writer = XbelWriter()
parentNode = self.node(index)
writer.write(buffer, parentNode)
stream << encodedData
urls.append(index.data(self.UrlRole))
mdata = QMimeData()
mdata.setData(self.MIMETYPE, data)
mdata.setUrls(urls)
return mdata
示例9: dropMimeData
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def dropMimeData(self, data, action, row, column, parent):
"""
Public method to accept the mime data of a drop action.
@param data reference to the mime data (QMimeData)
@param action drop action requested (Qt.DropAction)
@param row row number (integer)
@param column column number (integer)
@param parent index of the parent node (QModelIndex)
@return flag indicating successful acceptance of the data (boolean)
"""
if action == Qt.IgnoreAction:
return True
if column > 0:
return False
parentNode = self.node(parent)
if not data.hasFormat(self.MIMETYPE):
if not data.hasUrls():
return False
from .BookmarkNode import BookmarkNode
node = BookmarkNode(BookmarkNode.Bookmark, parentNode)
node.url = bytes(data.urls()[0].toEncoded()).decode()
if data.hasText():
node.title = data.text()
else:
node.title = node.url
self.__bookmarksManager.addBookmark(parentNode, node, row)
return True
ba = data.data(self.MIMETYPE)
stream = QDataStream(ba, QIODevice.ReadOnly)
if stream.atEnd():
return False
undoStack = self.__bookmarksManager.undoRedoStack()
undoStack.beginMacro("Move Bookmarks")
from .XbelReader import XbelReader
while not stream.atEnd():
encodedData = QByteArray()
stream >> encodedData
buffer = QBuffer(encodedData)
buffer.open(QIODevice.ReadOnly)
reader = XbelReader()
rootNode = reader.read(buffer)
for bookmarkNode in rootNode.children():
rootNode.remove(bookmarkNode)
row = max(0, row)
self.__bookmarksManager.addBookmark(
parentNode, bookmarkNode, row)
self.__endMacro = True
return True
示例10: image_and_format_from_data
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def image_and_format_from_data(data):
' Create an image object from the specified data which should be a bytestring and also return the format of the image '
ba = QByteArray(data)
buf = QBuffer(ba)
buf.open(QBuffer.ReadOnly)
r = QImageReader(buf)
fmt = bytes(r.format()).decode('utf-8')
return r.read(), fmt
示例11: take_screenshot
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def take_screenshot(self):
byte_array = QByteArray()
buffer = QBuffer(byte_array)
buffer.open(QIODevice.WriteOnly)
image = self.__screen.grabWindow(QApplication.desktop().winId())
image.save(buffer, "PNG")
return str(byte_array.toBase64())[1:]
示例12: fillImageFaster
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def fillImageFaster(self, begin, paint, current, image):
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
image.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
ImageDraw.floodfill(pil_im, begin, (paint.red(), paint.green(), paint.blue()))
self.image().image = QtGui.QImage(pil_im.convert("RGB").tobytes("raw", "RGB"), pil_im.size[0], pil_im.size[1], QtGui.QImage.Format_RGB888)
self.update()
示例13: scale
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def scale(image, width, height):
edited = QImage.fromData(image.data, format_for(image.mime))
if edited.isNull():
return image
scaled = edited.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
buffer = QBuffer()
buffer.open(QIODevice.WriteOnly)
scaled.save(buffer, format_for(image.mime))
buffer.close()
return Image(mime=image.mime, data=buffer.data(), desc=image.desc, type_=image.type)
示例14: sendMessage
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def sendMessage(self):
textbuf = QBuffer()
textbuf.open(QBuffer.ReadWrite)
messageText = QDataStream(textbuf)
messageText << self.ui.messageBox.text
size = textbuf.size()
if not self.shareMemory.create(size):
return
size = min(self.shareMemory.size(), size)
self.sharedMemory.lock()
示例15: sendDeleteRequest
# 需要导入模块: from PyQt5.QtCore import QBuffer [as 别名]
# 或者: from PyQt5.QtCore.QBuffer import open [as 别名]
def sendDeleteRequest(self, endpoint, data={}, params={}, headers={}):
buff = QBuffer()
buff.open(QBuffer.ReadWrite)
d = json.dumps(data).encode('utf-8')
buff.write(d)
buff.seek(0)
headers.update({"Content-Type":"application/json"})
content = self.sendRequest( endpoint, params,
'delete',
buff,
headers=headers
)
buff.close()
return content