本文整理汇总了Python中PyQt4.QtCore.QByteArray.append方法的典型用法代码示例。如果您正苦于以下问题:Python QByteArray.append方法的具体用法?Python QByteArray.append怎么用?Python QByteArray.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QByteArray
的用法示例。
在下文中一共展示了QByteArray.append方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FriendFeedRequest
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
class FriendFeedRequest(QObject):
def __init__(self, reply, feed = False, parent = None):
QObject.__init__(self, parent)
self.reply = reply
self.feed = feed
self.connect(self.reply, SIGNAL("readyRead()"), self.readData)
self.connect(self.reply, SIGNAL("finished()"), self.dataDone)
self.data = QByteArray()
def readData(self):
self.data.append(self.reply.readAll())
def dataDone(self):
if self.reply.error() != QNetworkReply.NoError:
self.emit(SIGNAL("error"), self.reply.error())
else:
self.data.append(self.reply.readAll())
result = simplejson.loads(str(self.data).decode("utf-8"))
if self.feed:
date_properties = frozenset(("updated", "published"))
for entry in result.get("entries", []):
entry["updated"] = self._parse_date(entry["updated"])
entry["published"] = self._parse_date(entry["published"])
for comment in entry.get("comments", []):
comment["date"] = self._parse_date(comment["date"])
for like in entry.get("likes", []):
like["date"] = self._parse_date(like["date"])
result["entries"].sort(key = lambda x:x["updated"], reverse = True)
self.emit(SIGNAL("ready"), result)
self.emit(SIGNAL("cleanup"), self)
def _parse_date(self, date_str):
rfc3339_date = "%Y-%m-%dT%H:%M:%SZ"
return datetime.datetime(*time.strptime(date_str, rfc3339_date)[:6])
示例2: send_ctrl_to_process
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def send_ctrl_to_process(self, letter):
char = chr("abcdefghijklmnopqrstuvwxyz".index(letter) + 1)
byte_array = QByteArray()
byte_array.append(char)
self.process.write(byte_array)
self.process.waitForBytesWritten(-1)
self.shell.write(locale_codec.toUnicode(byte_array), flush=True)
示例3: qstring2path
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def qstring2path (qs):
# BUG: this is ugly; might be properly handled w/PyQt4.6/Python2.6
qba= QByteArray ()
qba.append (qs)
s= str (qba)
return s
示例4: send_ctrl_to_process
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def send_ctrl_to_process(self, letter):
char = chr("abcdefghijklmnopqrstuvwxyz".index(letter) + 1)
byte_array = QByteArray()
byte_array.append(char)
self.process.write(byte_array)
self.process.waitForBytesWritten(-1)
self.shell.write(QString(byte_array))
示例5: mimeData
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def mimeData(self, items):
""" Returns QMimeData for drag and drop.
"""
logging.debug(self.__class__.__name__ + ": mimeData()")
mime = QMimeData()
encodedData = QByteArray()
for item in items:
encodedData.append(item.text(0))
mime.setData(self.mimeType(), encodedData)
return mime
示例6: do_ftp_put
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def do_ftp_put(self):
num = len(self.files)
for i in range(num):
file = self.files[i]
fhandle = QFile(file)
fhandle.open(QIODevice.ReadOnly)
byte_array = QByteArray()
byte_array.append(fhandle.readData(fhandle.size()))
fileinfo = QFileInfo(file)
filename = fileinfo.fileName()
self.ftp.put(byte_array, filename)
self.ftp.close()
示例7: ask_for_token
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def ask_for_token(c_id, c_secret, request_status=True):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if request_status is True:
request_status = False
return request, databyte
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
示例8: onPushButtonSendClicked
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def onPushButtonSendClicked(self):
if not self.__serial.isOpen:
self.__postText("E[?]: Port is not open.")
return
text = self.lineEditData.text().simplified()
if text.isEmpty():
self.__postText("E[?]: No input provided.")
return
self.__history.add(text)
data = QByteArray()
if self.checkBoxRawText.isChecked():
dataFormat = "S"
data = text.toLocal8Bit()
else:
INDEX_BASE = {0: 2, 1: 8, 2: 10, 3: 16}
index = self.comboBoxFormat.currentIndex()
base = INDEX_BASE.get(index, None)
if not base:
self.__postText("E[?]: Invalid base of a number.")
try:
values = stringToBytes(str(text), base)
except ValueError as error:
self.__postText("E[?]: Incorrect input: <%s>." % str(error).capitalize())
for value in values:
data.append(chr(value))
text = bytesToString(values, base, self.checkBoxLeadingZeroes.isChecked())
INDEX_FORMAT = {0: "B", 1: "O", 2: "D", 3: "H"}
dataFormat = INDEX_FORMAT.get(index, None)
if not dataFormat:
self.__postText("E[?]: Invalid data format.")
self.lineEditData.clear()
self.__postText("T[%s:%s]: %s" % (dataFormat, len(data), text))
self.__serial.write(data)
示例9: open
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def open(self, url, post_data=None, headers={}, receiver=None):
request = QNetworkRequest(QUrl(url))
if post_data:
debug.debug('post %s' % url)
postData = QByteArray()
for key, var in post_data.items():
postData.append('%s=%s&' % (key, var))
for header, var in headers.items():
request.setRawHeader(header, var)
reply = self.netWorkMgr.post(request, postData)
else:
debug.debug('get %s' % url)
for header, var in headers.items():
request.setRawHeader(header, var)
reply = self.netWorkMgr.get(request)
if receiver:
reply.finished.connect(receiver)
else:
receiver = self.netWorkMgr.parent()
reply.finished.connect(receiver.replyFinished)
示例10: FileDownloader
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
class FileDownloader(object):
"""The blueprint for downloading file from url."""
def __init__(self, manager, url, output_path, progress_dialog=None):
"""Constructor of the class.
:param manager: QNetworkAccessManager instance to handle downloading.
:type manager: QNetworkAccessManager
:param url: URL of file.
:type url: str
:param output_path: Output path.
:type output_path: str
:param progress_dialog: Progress dialog widget.
:type progress_dialog: QWidget
"""
self.manager = manager
self.url = url
self.output_path = output_path
self.progress_dialog = progress_dialog
self.output_file = None
self.reply = None
self.downloaded_file_buffer = None
self.finished_flag = False
def download(self):
"""Downloading the file.
:returns: True if success, otherwise returns a tuple with format like
this (QNetworkReply.NetworkError, error_message)
:raises: IOError - when cannot create output_path
"""
# Prepare output path
self.output_file = QFile(self.output_path)
if not self.output_file.open(QFile.WriteOnly):
raise IOError(self.output_file.errorString())
# Prepare downloaded buffer
self.downloaded_file_buffer = QByteArray()
# Request the url
request = QNetworkRequest(QUrl(self.url))
self.reply = self.manager.get(request)
self.reply.readyRead.connect(self.get_buffer)
self.reply.finished.connect(self.write_data)
if self.progress_dialog:
# progress bar
def progress_event(received, total):
"""Update progress.
:param received: Data received so far.
:type received: int
:param total: Total expected data.
:type total: int
"""
# noinspection PyArgumentList
QCoreApplication.processEvents()
label_text = "%s / %s" % (received, total)
self.progress_dialog.setLabelText(label_text)
self.progress_dialog.setMaximum(total)
self.progress_dialog.setValue(received)
# cancel
def cancel_action():
"""Cancel download."""
self.reply.abort()
self.reply.downloadProgress.connect(progress_event)
self.progress_dialog.canceled.connect(cancel_action)
# Wait until finished
# On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
# returns False even after finished slot is called. So, that's why we
# are adding self.finished_flag (see #864)
while not self.reply.isFinished() and not self.finished_flag:
# noinspection PyArgumentList
QCoreApplication.processEvents()
result = self.reply.error()
if result == QNetworkReply.NoError:
return True, None
else:
return result, str(self.reply.errorString())
def get_buffer(self):
"""Get buffer from self.reply and store it to our buffer container."""
buffer_size = self.reply.size()
data = self.reply.read(buffer_size)
self.downloaded_file_buffer.append(data)
def write_data(self):
"""Write data to a file."""
self.output_file.write(self.downloaded_file_buffer)
self.output_file.close()
#.........这里部分代码省略.........
示例11: xmlDownloaded
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
def xmlDownloaded(self):
""" populate the plugins object with the fetched data """
reply = self.sender()
reposName = reply.property('reposName')
if reply.error() != QNetworkReply.NoError: # fetching failed
self.mRepositories[reposName]["state"] = 3
self.mRepositories[reposName]["error"] = reply.errorString()
if reply.error() == QNetworkReply.OperationCanceledError:
self.mRepositories[reposName]["error"] += "\n\n" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window.")
else:
reposXML = QDomDocument()
content = reply.readAll()
# Fix lonely ampersands in metadata
a = QByteArray()
a.append("& ")
b = QByteArray()
b.append("& ")
content = content.replace(a, b)
reposXML.setContent(content)
pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
if pluginNodes.size():
for i in range(pluginNodes.size()):
fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip()
if not fileName:
fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName()
name = fileName.partition(".")[0]
experimental = False
if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE", "YES"]:
experimental = True
deprecated = False
if pluginNodes.item(i).firstChildElement("deprecated").text().strip().upper() in ["TRUE", "YES"]:
deprecated = True
icon = pluginNodes.item(i).firstChildElement("icon").text().strip()
if icon and not icon.startswith("http"):
icon = "http://%s/%s" % (QUrl(self.mRepositories[reposName]["url"]).host(), icon)
if pluginNodes.item(i).toElement().hasAttribute("plugin_id"):
plugin_id = pluginNodes.item(i).toElement().attribute("plugin_id")
else:
plugin_id = None
plugin = {
"id": name,
"plugin_id": plugin_id,
"name": pluginNodes.item(i).toElement().attribute("name"),
"version_available": pluginNodes.item(i).toElement().attribute("version"),
"description": pluginNodes.item(i).firstChildElement("description").text().strip(),
"about": pluginNodes.item(i).firstChildElement("about").text().strip(),
"author_name": pluginNodes.item(i).firstChildElement("author_name").text().strip(),
"homepage": pluginNodes.item(i).firstChildElement("homepage").text().strip(),
"download_url": pluginNodes.item(i).firstChildElement("download_url").text().strip(),
"category": pluginNodes.item(i).firstChildElement("category").text().strip(),
"tags": pluginNodes.item(i).firstChildElement("tags").text().strip(),
"changelog": pluginNodes.item(i).firstChildElement("changelog").text().strip(),
"author_email": pluginNodes.item(i).firstChildElement("author_email").text().strip(),
"tracker": pluginNodes.item(i).firstChildElement("tracker").text().strip(),
"code_repository": pluginNodes.item(i).firstChildElement("repository").text().strip(),
"downloads": pluginNodes.item(i).firstChildElement("downloads").text().strip(),
"average_vote": pluginNodes.item(i).firstChildElement("average_vote").text().strip(),
"rating_votes": pluginNodes.item(i).firstChildElement("rating_votes").text().strip(),
"icon": icon,
"experimental": experimental,
"deprecated": deprecated,
"filename": fileName,
"installed": False,
"available": True,
"status": "not installed",
"error": "",
"error_details": "",
"version_installed": "",
"zip_repository": reposName,
"library": "",
"readonly": False
}
qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip()
if not qgisMinimumVersion:
qgisMinimumVersion = "2"
qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip()
if not qgisMaximumVersion:
qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
#if compatible, add the plugin to the list
if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]:
if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
#add the plugin to the cache
plugins.addFromRepository(plugin)
self.mRepositories[reposName]["state"] = 2
else:
# no plugin metadata found
self.mRepositories[reposName]["state"] = 3
if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200:
self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options.")
else:
self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Status code:") + " %d %s" % (
reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)
)
self.repositoryFetched.emit(reposName)
# is the checking done?
#.........这里部分代码省略.........
示例12: FileDownloader
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
#.........这里部分代码省略.........
:param received: Data received so far.
:type received: int
:param total: Total expected data.
:type total: int
"""
# noinspection PyArgumentList
QCoreApplication.processEvents()
self.progress_dialog.adjustSize()
human_received = humanize_file_size(received)
human_total = humanize_file_size(total)
label_text = tr("%s : %s of %s" % (
self.prefix_text, human_received, human_total))
self.progress_dialog.setLabelText(label_text)
self.progress_dialog.setMaximum(total)
self.progress_dialog.setValue(received)
# cancel
def cancel_action():
"""Cancel download."""
self.reply.abort()
self.reply.deleteLater()
self.reply.downloadProgress.connect(progress_event)
self.progress_dialog.canceled.connect(cancel_action)
# Wait until finished
# On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
# returns False even after finished slot is called. So, that's why we
# are adding self.finished_flag (see #864)
while not self.reply.isFinished() and not self.finished_flag:
# noinspection PyArgumentList
QCoreApplication.processEvents()
result = self.reply.error()
try:
http_code = int(self.reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute))
except TypeError:
# If the user cancels the request, the HTTP response will be None.
http_code = None
self.reply.abort()
self.reply.deleteLater()
if result == QNetworkReply.NoError:
return True, None
elif result == QNetworkReply.UnknownNetworkError:
return False, tr(
'The network is unreachable. Please check your internet '
'connection.')
elif http_code == 408:
msg = tr(
'Sorry, the server aborted your request. '
'Please try a smaller area.')
LOGGER.debug(msg)
return False, msg
elif http_code == 509:
msg = tr(
'Sorry, the server is currently busy with another request. '
'Please try again in a few minutes.')
LOGGER.debug(msg)
return False, msg
elif result == QNetworkReply.ProtocolUnknownError or \
result == QNetworkReply.HostNotFoundError:
LOGGER.exception('Host not found : %s' % self.url.encodedHost())
return False, tr(
'Sorry, the server is unreachable. Please try again later.')
elif result == QNetworkReply.ContentNotFoundError:
LOGGER.exception('Path not found : %s' % self.url.path())
return False, tr('Sorry, the layer was not found on the server.')
else:
return result, self.reply.errorString()
def get_buffer(self):
"""Get buffer from self.reply and store it to our buffer container."""
buffer_size = self.reply.size()
data = self.reply.read(buffer_size)
self.downloaded_file_buffer.append(data)
def write_data(self):
"""Write data to a file."""
self.output_file.write(self.downloaded_file_buffer)
self.output_file.close()
self.finished_flag = True
def request_timeout(self):
"""The request timed out."""
if self.progress_dialog:
self.progress_dialog.hide()
示例13: Window
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [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))
示例14: ServicoScreenshot
# 需要导入模块: from PyQt4.QtCore import QByteArray [as 别名]
# 或者: from PyQt4.QtCore.QByteArray import append [as 别名]
class ServicoScreenshot(ServicoInformacao):
telaRecebida = pyqtSignal(str, QPixmap)
ENVIANDO_PARTE_IMAGEM = 40
ENVIANDO_FINAL_IMAGEM = 41
PARTE_RECEBIDA = 42
def __init__(self, portaReceber=4002, portaResponder=4003, parent=None):
super().__init__(portaReceber=portaReceber, portaResponder=portaResponder, parent=parent)
self._arrayEnviar = QByteArray()
self._recebendoPartesImagem = []
def _receberInformacaoTipoValor(self, de, tipo, valor):
# Recebendo
print(tipo)
if tipo == ServicoScreenshot.ENVIANDO_PARTE_IMAGEM:
self.setPara(de)
self._arrayEnviar.append(valor)
print("ENVIANDO RECEBIDA")
self.enviarInformacaoTipoValor(ServicoScreenshot.PARTE_RECEBIDA, None)
elif tipo == ServicoScreenshot.ENVIANDO_FINAL_IMAGEM:
imagem = self._imagemByteArray(self._arrayEnviar)
self._arrayEnviar.clear()
self.telaRecebida.emit(de, imagem)
# Enviando
elif tipo == ServicoScreenshot.PARTE_RECEBIDA:
self._enviarParte()
super()._receberInformacaoTipoValor(de, tipo, valor)
def _imagemByteArray(self, array):
data = QDataStream(array)
image = QPixmap()
data >> image
return image
def _dividirArray(self, array, tam=30000):
lista = []
partes = int(array.length() / tam)
for i in range(partes):
lista.append(array.mid(tam * i, tam))
if tam * partes != array.length():
lista.append(array.mid(tam * partes))
return lista
def _enviarParte(self):
self.enviarInformacaoTipoValor(ServicoScreenshot.ENVIANDO_PARTE_IMAGEM, self._recebendoPartesImagem.pop(0))
print("PARTE")
if not self._recebendoPartesImagem:
print("FINAL")
self.enviarInformacaoTipoValor(ServicoScreenshot.ENVIANDO_FINAL_IMAGEM, None)
def enviarScreenshot(self):
self.enviarImagem(QPixmap.grabWindow(QApplication.desktop().winId()))
def enviarImagem(self, imagem):
array = QByteArray()
data = QDataStream(array, QIODevice.WriteOnly)
data << imagem
self._recebendoPartesImagem = self._dividirArray(array)
self._enviarParte()