本文整理汇总了Python中PyQt4.QtCore.QBuffer.setData方法的典型用法代码示例。如果您正苦于以下问题:Python QBuffer.setData方法的具体用法?Python QBuffer.setData怎么用?Python QBuffer.setData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QBuffer
的用法示例。
在下文中一共展示了QBuffer.setData方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: request
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
def request(self, iri, method="GET", extra_headers=None,
oauth_credentials=None, post_content=None):
"""Return a deferred that will be fired with a Response object."""
uri = self.iri_to_uri(iri)
request = QNetworkRequest(QUrl(uri))
request.setSslConfiguration(self.ssl_config)
headers = yield self.build_request_headers(uri, method, extra_headers,
oauth_credentials)
for key, value in headers.items():
request.setRawHeader(key, value)
post_buffer = QBuffer()
post_buffer.setData(post_content)
try:
result = yield self._perform_request(request, method, post_buffer)
except ProxyUnauthorizedError as e:
app_proxy = QNetworkProxy.applicationProxy()
proxy_host = app_proxy.hostName() if app_proxy else "proxy server"
got_creds = yield self.request_proxy_auth_credentials(
proxy_host, self.proxy_retry)
if got_creds:
self.proxy_retry = True
result = yield self.request(iri, method, extra_headers,
oauth_credentials, post_content)
else:
excp = WebClientError('Proxy creds needed.', e)
defer.returnValue(excp)
defer.returnValue(result)
示例2: __init__
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
def __init__(self):
QWidget.__init__(self)
self.tray = Tray(self)
self.setMinimumSize(QSize(320, 200))
self.setWindowFlags(Qt.Popup|Qt.FramelessWindowHint)
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.setMargin(1)
self.text = QTextBrowser(self)
self.text.setReadOnly(True)
self.text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.text.setOpenExternalLinks(True)
self.verticalLayout.addWidget(self.text)
self.text.textChanged.connect(self.on_text_changed)
self.notify = Notify(self)
self.movie = QMovie()
dev = QBuffer()
dev.setData(QByteArray.fromBase64(CHECK_IMAGE))
dev.open(QBuffer.ReadOnly)
dev.setParent(self.movie)
self.movie.setDevice(dev)
self.movie.frameChanged.connect(self.on_frame_changed)
self.realized = False
self.show()
示例3: saveTiles
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
def saveTiles(self):
if self.tiles is None:
QMessageBox.warning(None, self.plugin.pluginName, self.tr("No tiles have been downloaded."))
return
# Let the user choose the directory to save to
directory = QFileDialog.getExistingDirectory(caption=self.tr("{}: Choose directory").format(self.layerDef.title))
if not directory:
# User cancelled the directory selection
return
# Build the content of the .aux.xml file containing the projection info
projection_string = (self.crs().toWkt())
pam_string = '<PAMDataset>\n' + \
'<SRS>{}</SRS>\n'.format(projection_string) + \
'</PAMDataset>'
for tile in self.tiles.tiles.values():
# Figure out the file format extension
reader = QImageReader()
buffer = QBuffer()
buffer.setData(tile.data)
buffer.open(QIODevice.ReadOnly)
extension = str(reader.imageFormat(buffer))
# Build the file name of the image file
image_file_name = "{}-{}-{}.{}".format(tile.x, tile.y, tile.zoom, extension)
image_file_path = join(directory, image_file_name)
# Save the image file
with open(image_file_path, 'wb') as image_file:
image_file.write(tile.data)
# Save the .aux.xml
with open(image_file_path + '.aux.xml', 'w') as aux_file:
aux_file.write(pam_string)
# Save the world file containing the georeferencing information
tile_rect = self.tiles.serviceInfo.getTileRect(tile.zoom, tile.x, tile.y)
tile_size = self.tiles.TILE_SIZE
with open(image_file_path + 'w', 'w') as world_file:
world_file.writelines([
str(tile_rect.width() / tile_size) + '\n',
'0\n',
'0\n',
str(-tile_rect.height() / tile_size) + '\n',
str(tile_rect.xMinimum()) + '\n',
str(tile_rect.yMaximum()) + '\n'
])
# Done
msg = self.tr("Tiles have been saved.")
self.showMessageBar(msg, QgsMessageBar.INFO, 2)
示例4: Connection
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
class Connection(QTcpSocket):
"""Abstracts server-client connections.
Whenever data is received, a Connection attempts to parse a Message and arguments from the data, and emits messageReceived for each parsed message. See QTcpSocket documentation for other members."""
messageSent = pyqtSignal(int, list)
"""Emitted whenever a message is sent. Arguments: the message type, list of arguments."""
messageReceived = pyqtSignal(int, list)
"""Emitted whenever a message is recieved. Arguments: the message type, list of arguments."""
messageReceived2 = pyqtSignal()
def __init__(self, id = None, client = False, parent = None):
"""Creates a connection.
id -- Optional socket descriptor.
client -- Whether this connection is opened from the client side or server side.
parent -- Parent object."""
QTcpSocket.__init__(self, parent)
if id:
if not self.setSocketDescriptor(id):
self.done()
return
self.id = id
self.player = None
self.client = client
self.buffer = QBuffer()
self.buffer.open(QBuffer.ReadWrite)
self.readyRead.connect(self._readIncomingData)
def abort(self):
"""Aborts the connection."""
super(Connection, self).abort()
def _readIncomingData(self):
bytesWritten = self.buffer.write(self.readAll())
self.buffer.seek(0)
result = self._parse()
bytesRead = 0
while result:
bytesRead += result[2]
msg, args = result[:2]
if self.client:
log.debug("Received %s %s", msg, args)
elif self.player and self.player.name:
log.debug("Received %s %s from %s", msg, args, self.player)
else:
log.debug("Received %s %s from %s", msg, args, self.peerAddress().toString())
self.messageReceived.emit(msg, args)
self.messageReceived2.emit()
result = self._parse()
#remove the successfully parsed data
size = self.buffer.size()
self.buffer.close()
data = self.buffer.data()
self.buffer.setData(data.right(size - bytesRead))
self.buffer.open(QBuffer.ReadWrite)
self.buffer.seek(self.buffer.size())
def _parse(self):
if self.buffer.bytesAvailable() >= 4:
stream = QDataStream(self.buffer)
msg = Message.fromInt(stream.readInt32())
if msg == None:
return
args = []
bytesRead = 4
for aType in msg.argTypes:
if aType == str:
if self.buffer.bytesAvailable() < 4:
return
length = stream.readInt32()
if self.buffer.bytesAvailable() < length:
return
args.append(stream.readRawData(length))
bytesRead += 4 + length
elif aType == int:
if self.buffer.bytesAvailable() < 4:
return
args.append(stream.readInt32())
bytesRead += 4
elif aType == long:
if self.buffer.bytesAvailable() < 8:
return
args.append(stream.readInt64())
bytesRead += 8
return (msg, args, bytesRead)
def sendMessage(self, msg, args, id = None):
"""Sends a message.
msg -- The message type.
args -- List of message arguments.
id -- An optional socket descriptor. If specified, then the message will only be sent if this connection's socket descriptor matches id."""
if id:
if self.socketDescriptor() != id:
return
msg = Message.fromInt(msg)
if not msg.validateArgs(args):
log.warning("Message %d and args %s have invalid types. Message not sent.", msg, args)
return
if self.client:
#.........这里部分代码省略.........
示例5: Window
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
format = QAudioFormat()
format.setChannels(1)
format.setFrequency(22050)
format.setSampleSize(16)
format.setCodec("audio/pcm")
format.setByteOrder(QAudioFormat.LittleEndian)
format.setSampleType(QAudioFormat.SignedInt)
self.output = QAudioOutput(format, self)
self.frequency = 440
self.volume = 0
self.buffer = QBuffer()
self.data = QByteArray()
self.deviceLineEdit = QLineEdit()
self.deviceLineEdit.setReadOnly(True)
self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName())
self.pitchSlider = QSlider(Qt.Horizontal)
self.pitchSlider.setMaximum(100)
self.volumeSlider = QSlider(Qt.Horizontal)
self.volumeSlider.setMaximum(32767)
self.volumeSlider.setPageStep(1024)
self.playButton = QPushButton(self.tr("&Play"))
self.pitchSlider.valueChanged.connect(self.changeFrequency)
self.volumeSlider.valueChanged.connect(self.changeVolume)
self.playButton.clicked.connect(self.play)
formLayout = QFormLayout()
formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)
buttonLayout = QVBoxLayout()
buttonLayout.addWidget(self.playButton)
buttonLayout.addStretch()
horizontalLayout = QHBoxLayout(self)
horizontalLayout.addLayout(formLayout)
horizontalLayout.addLayout(buttonLayout)
def changeFrequency(self, value):
self.frequency = 440 + (value * 2)
def play(self):
if self.output.state() == QAudio.ActiveState:
self.output.stop()
if self.buffer.isOpen():
self.buffer.close()
self.createData()
self.buffer.setData(self.data)
self.buffer.open(QIODevice.ReadOnly)
self.buffer.seek(0)
self.output.start(self.buffer)
def changeVolume(self, value):
self.volume = value
def createData(self):
# Create 2 seconds of data with 22050 samples per second, each sample
# being 16 bits (2 bytes).
self.data.clear()
for i in xrange(2 * 22050):
t = i / 22050.0
value = int(self.volume * sin(2 * pi * self.frequency * t))
self.data.append(struct.pack("<h", value))
示例6: send
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import setData [as 别名]
def send(self, method, url, headers, body, context = None):
qurl = QUrl.fromEncoded(url)
request = QNetworkRequest()
request.setUrl(qurl)
method = self.translate_method(method, request)
host, useragent, content_type = None, None, None
for name, value in headers.items():
lname = name.lower()
if 'user-agent' == lname:
useragent = value
elif 'host' == lname:
host = value
elif 'content-type' == lname:
content_type = value
elif 'content-length' == lname:
continue
request.setRawHeader(name, value)
if not host:
request.setRawHeader('Host', str(qurl.host()))
if not useragent:
request.setRawHeader('User-Agent', self.framework.useragent())
if 'POST' == method and not content_type:
request.setRawHeader('Content-Type', 'application/x-www-form-urlencoded')
if not body:
if method in ('POST', 'PUT', 'CUSTOM'): # TODO: determine specific methods that expect content?
body = ''
else:
device = None
if method in ('GET', 'HEAD', 'DELETE'):
# can't have body, because not supported by Qt network logic
body = None
device = None
if body is not None:
request.setRawHeader('Content-Length', str(len(body)))
data = QByteArray(body)
device = QBuffer(self)
device.setData(data)
device.open(QIODevice.ReadOnly)
request.setAttribute(request.CacheLoadControlAttribute, request.AlwaysNetwork)
if 'GET' == method:
reply = self.networkAccessManager.get(request)
elif 'HEAD' == method:
reply = self.networkAccessManager.head(request)
elif 'DELETE' == method:
reply = self.networkAccessManager.head(request)
elif 'POST' == method:
reply = self.networkAccessManager.post(request, device)
elif 'PUT' == method:
reply = self.networkAccessManager.put(request, device)
else:
reply = self.networkAccessManager.sendCustomRequest(request, method, device)
response = NetworkResponse(self.framework, self.callback, reply, context, self)
return NetworkRequest(request, reply, response, context, self)