本文整理汇总了C++中QByteArray::constData方法的典型用法代码示例。如果您正苦于以下问题:C++ QByteArray::constData方法的具体用法?C++ QByteArray::constData怎么用?C++ QByteArray::constData使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QByteArray
的用法示例。
在下文中一共展示了QByteArray::constData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: fromName
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
QHostInfo results;
#if defined(QHOSTINFO_DEBUG)
qDebug("QHostInfoAgent::fromName(%s) looking up...",
hostName.toLatin1().constData());
#endif
// Load res_init on demand.
static volatile bool triedResolve = false;
if (!triedResolve) {
QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
if (!triedResolve) {
resolveLibrary();
triedResolve = true;
}
}
// If res_init is available, poll it.
if (local_res_init)
local_res_init();
QHostAddress address;
if (address.setAddress(hostName)) {
// Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
sockaddr_in sa4;
#ifndef QT_NO_IPV6
sockaddr_in6 sa6;
#endif
sockaddr *sa = 0;
QT_SOCKLEN_T saSize = 0;
if (address.protocol() == QAbstractSocket::IPv4Protocol) {
sa = (sockaddr *)&sa4;
saSize = sizeof(sa4);
memset(&sa4, 0, sizeof(sa4));
sa4.sin_family = AF_INET;
sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
}
#ifndef QT_NO_IPV6
else {
sa = (sockaddr *)&sa6;
saSize = sizeof(sa6);
memset(&sa6, 0, sizeof(sa6));
sa6.sin6_family = AF_INET6;
memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
}
#endif
char hbuf[NI_MAXHOST];
if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
results.setHostName(QString::fromLatin1(hbuf));
#else
in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
if (ent)
results.setHostName(QString::fromLatin1(ent->h_name));
#endif
if (results.hostName().isEmpty())
results.setHostName(address.toString());
results.setAddresses(QList<QHostAddress>() << address);
return results;
}
// IDN support
QByteArray aceHostname = QUrl::toAce(hostName);
results.setHostName(hostName);
if (aceHostname.isEmpty()) {
results.setError(QHostInfo::HostNotFound);
results.setErrorString(hostName.isEmpty() ?
QCoreApplication::translate("QHostInfoAgent", "No host name given") :
QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
return results;
}
#if !defined (QT_NO_GETADDRINFO)
// Call getaddrinfo, and place all IPv4 addresses at the start and
// the IPv6 addresses at the end of the address list in results.
addrinfo *res = 0;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
hints.ai_flags = Q_ADDRCONFIG;
#endif
int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
if (result == EAI_BADFLAGS) {
// if the lookup failed with AI_ADDRCONFIG set, try again without it
hints.ai_flags = 0;
result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
}
# endif
if (result == 0) {
addrinfo *node = res;
//.........这里部分代码省略.........
示例2: writeMessage
void RemotePeer::writeMessage(const QByteArray &msg)
{
quint32 size = qToBigEndian<quint32>(msg.size());
_compressor->write((const char*)&size, 4, Compressor::NoFlush);
_compressor->write(msg.constData(), msg.size());
}
示例3: decode
bool FLACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
QProcess process;
QStringList args;
args << "-d" << "-F" << "-f";
args << "-o" << QDir::toNativeSeparators(outputFile);
args << QDir::toNativeSeparators(sourceFile);
if(!startProcess(process, m_binary, args))
{
return false;
}
bool bTimeout = false;
bool bAborted = false;
QRegExp regExp("\\s(\\d+)% complete");
while(process.state() != QProcess::NotRunning)
{
if(*abortFlag)
{
process.kill();
bAborted = true;
emit messageLogged("\nABORTED BY USER !!!");
break;
}
process.waitForReadyRead(m_processTimeoutInterval);
if(!process.bytesAvailable() && process.state() == QProcess::Running)
{
process.kill();
qWarning("FLAC process timed out <-- killing!");
emit messageLogged("\nPROCESS TIMEOUT !!!");
bTimeout = true;
break;
}
while(process.bytesAvailable() > 0)
{
QByteArray line = process.readLine();
QString text = QString::fromUtf8(line.constData()).simplified();
if(regExp.lastIndexIn(text) >= 0)
{
bool ok = false;
int progress = regExp.cap(1).toInt(&ok);
if(ok) emit statusUpdated(progress);
}
else if(!text.isEmpty())
{
emit messageLogged(text);
}
}
}
process.waitForFinished();
if(process.state() != QProcess::NotRunning)
{
process.kill();
process.waitForFinished(-1);
}
emit statusUpdated(100);
emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
if(bTimeout || bAborted || process.exitStatus() != QProcess::NormalExit || QFileInfo(outputFile).size() == 0)
{
return false;
}
return true;
}
示例4: load_filters_plugins
void Lib_initializer::load_filters_plugins()
{
SmartPtr<Named_interface> ni = Root::instance()->interface(topLevelInputFilters_manager);
Manager* mng = dynamic_cast<Manager*> (ni.raw_ptr());
appli_assert( mng );
std::string filters_plugin_path(mng->plugin_path());
QString path(filters_plugin_path.c_str());
// Loop on all the library files (.so or .dll) in directory "path"
QDir dir(path);
if (!dir.exists())
return;
QStringList filters;
filters << "*.so" << "*.dll";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files);
const QFileInfoList list = dir.entryInfoList();
if (list.empty())
{
GsTLlog << "No filter plugins found.\n" << gstlIO::end;
return;
}
QFileInfoList::const_iterator it = list.begin();
const QFileInfo* f_info;
for (; it != list.end(); ++it)
{
f_info = &(*it);
// QLibrary wants the absolute path
QString tmp = path + "/" + f_info->fileName();
QByteArray tmps = tmp.toLatin1();
appli_message( "loading file: " << tmps.constData());
QLibrary lib(path + "/" + f_info->fileName());
//lib.setAutoUnload( false );
lib.load();
if (!lib.isLoaded())
{
appli_warning( "library not loaded " << std::endl );
continue;
}
typedef int (*Init_func_prototype)(void);
// The function must be called [filename]_init()
// QString init_func_name( f_info->baseName() + "_init" );
// The function must be called plugin_init()
QString init_func_name = "plugin_init";
QByteArray tmp1 = init_func_name.toLatin1();
Init_func_prototype init_func = (Init_func_prototype) lib.resolve(tmp1.constData());
if (init_func)
init_func();
else
{
QByteArray s = init_func_name.toLatin1();
appli_warning( "unable to resolve symbol " << s.constData() );
}
}
}
示例5: matchString
static bool matchString(const QMimeMagicRulePrivate *d, const QByteArray &data)
{
const int rangeLength = d->endPos - d->startPos + 1;
return QMimeMagicRule::matchSubstring(data.constData(), data.size(), d->startPos, rangeLength, d->pattern.size(), d->pattern.constData(), d->mask.constData());
}
示例6: onLoad
void VoiceMessagesLoader::onLoad(AudioData *audio) {
bool started = false;
int32 audioindex = -1;
Loader *l = 0;
Loaders::iterator j = _loaders.end();
{
QMutexLocker lock(&voicemsgsMutex);
VoiceMessages *voice = audioVoice();
if (!voice) return;
for (int32 i = 0; i < AudioVoiceMsgSimultaneously; ++i) {
VoiceMessages::Msg &m(voice->_data[i]);
if (m.audio != audio || !m.loading) continue;
audioindex = i;
j = _loaders.find(audio);
if (j != _loaders.end() && (j.value()->fname != m.fname || j.value()->data.size() != m.data.size())) {
delete j.value();
_loaders.erase(j);
j = _loaders.end();
}
if (j == _loaders.end()) {
l = (j = _loaders.insert(audio, new Loader())).value();
l->fname = m.fname;
l->data = m.data;
int ret;
if (m.data.isEmpty()) {
l->file = op_open_file(m.fname.toUtf8().constData(), &ret);
} else {
l->file = op_open_memory((const unsigned char*)m.data.constData(), m.data.size(), &ret);
}
if (!l->file) {
LOG(("Audio Error: op_open_file failed for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(ret));
m.state = VoiceMessageStopped;
return loadError(j);
}
ogg_int64_t duration = op_pcm_total(l->file, -1);
if (duration < 0) {
LOG(("Audio Error: op_pcm_total failed to get full duration for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(duration));
m.state = VoiceMessageStopped;
return loadError(j);
}
m.duration = duration;
m.skipStart = 0;
m.skipEnd = duration;
m.position = 0;
m.started = 0;
started = true;
} else {
if (!m.skipEnd) continue;
l = j.value();
}
break;
}
}
if (j == _loaders.end()) {
LOG(("Audio Error: trying to load part of audio, that is not playing at the moment"));
emit error(audio);
return;
}
if (started) {
l->pcm_offset = op_pcm_tell(l->file);
l->pcm_print_offset = l->pcm_offset - AudioVoiceMsgFrequency;
}
bool finished = false;
DEBUG_LOG(("Audio Info: reading buffer for file '%1', data size '%2', current pcm_offset %3").arg(l->fname).arg(l->data.size()).arg(l->pcm_offset));
QByteArray result;
int64 samplesAdded = 0;
while (result.size() < AudioVoiceMsgBufferSize) {
opus_int16 pcm[AudioVoiceMsgFrequency * AudioVoiceMsgChannels];
int ret = op_read_stereo(l->file, pcm, sizeof(pcm) / sizeof(*pcm));
if (ret < 0) {
{
QMutexLocker lock(&voicemsgsMutex);
VoiceMessages *voice = audioVoice();
if (voice) {
VoiceMessages::Msg &m(voice->_data[audioindex]);
if (m.audio == audio) {
m.state = VoiceMessageStopped;
}
}
}
LOG(("Audio Error: op_read_stereo failed, error code %1").arg(ret));
return loadError(j);
}
int li = op_current_link(l->file);
if (li != l->prev_li) {
const OpusHead *head = op_head(l->file, li);
const OpusTags *tags = op_tags(l->file, li);
for (int32 ci = 0; ci < tags->comments; ++ci) {
const char *comment = tags->user_comments[ci];
if (opus_tagncompare("METADATA_BLOCK_PICTURE", 22, comment) == 0) {
OpusPictureTag pic;
int err = opus_picture_tag_parse(&pic, comment);
//.........这里部分代码省略.........
示例7: processDatagrams
//.........这里部分代码省略.........
Q_ARG(QByteArray, incomingPacket));
}
// update having heard from the audio-mixer and record the bytes received
SharedNodePointer audioMixer = nodeList->sendingNodeForPacket(incomingPacket);
if (audioMixer) {
audioMixer->setLastHeardMicrostamp(usecTimestampNow());
audioMixer->recordBytesReceived(incomingPacket.size());
}
break;
}
case PacketTypeEntityAddResponse:
// this will keep creatorTokenIDs to IDs mapped correctly
EntityItemID::handleAddEntityResponse(incomingPacket);
application->getEntities()->getTree()->handleAddEntityResponse(incomingPacket);
break;
case PacketTypeEntityData:
case PacketTypeEntityErase:
case PacketTypeOctreeStats:
case PacketTypeEnvironmentData: {
PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings),
"Application::networkReceive()... _octreeProcessor.queueReceivedPacket()");
SharedNodePointer matchedNode = DependencyManager::get<NodeList>()->sendingNodeForPacket(incomingPacket);
if (matchedNode) {
// add this packet to our list of octree packets and process them on the octree data processing
application->_octreeProcessor.queueReceivedPacket(matchedNode, incomingPacket);
}
break;
}
case PacketTypeMetavoxelData:
nodeList->findNodeAndUpdateWithDataFromPacket(incomingPacket);
break;
case PacketTypeBulkAvatarData:
case PacketTypeKillAvatar:
case PacketTypeAvatarIdentity:
case PacketTypeAvatarBillboard: {
// update having heard from the avatar-mixer and record the bytes received
SharedNodePointer avatarMixer = nodeList->sendingNodeForPacket(incomingPacket);
if (avatarMixer) {
avatarMixer->setLastHeardMicrostamp(usecTimestampNow());
avatarMixer->recordBytesReceived(incomingPacket.size());
QMetaObject::invokeMethod(&application->getAvatarManager(), "processAvatarMixerDatagram",
Q_ARG(const QByteArray&, incomingPacket),
Q_ARG(const QWeakPointer<Node>&, avatarMixer));
}
application->_bandwidthMeter.inputStream(BandwidthMeter::AVATARS).updateValue(incomingPacket.size());
break;
}
case PacketTypeDomainConnectionDenied: {
// output to the log so the user knows they got a denied connection request
// and check and signal for an access token so that we can make sure they are logged in
qDebug() << "The domain-server denied a connection request.";
qDebug() << "You may need to re-log to generate a keypair so you can provide a username signature.";
AccountManager::getInstance().checkAndSignalForAccessToken();
break;
}
case PacketTypeNoisyMute:
case PacketTypeMuteEnvironment: {
bool mute = !DependencyManager::get<Audio>()->isMuted();
if (incomingType == PacketTypeMuteEnvironment) {
glm::vec3 position;
float radius, distance;
int headerSize = numBytesForPacketHeaderGivenPacketType(PacketTypeMuteEnvironment);
memcpy(&position, incomingPacket.constData() + headerSize, sizeof(glm::vec3));
memcpy(&radius, incomingPacket.constData() + headerSize + sizeof(glm::vec3), sizeof(float));
distance = glm::distance(Application::getInstance()->getAvatar()->getPosition(), position);
mute = mute && (distance < radius);
}
if (mute) {
DependencyManager::get<Audio>()->toggleMute();
if (incomingType == PacketTypeMuteEnvironment) {
AudioScriptingInterface::getInstance().environmentMuted();
} else {
AudioScriptingInterface::getInstance().mutedByMixer();
}
}
break;
}
case PacketTypeEntityEditNack:
if (!Menu::getInstance()->isOptionChecked(MenuOption::DisableNackPackets)) {
application->_entityEditSender.processNackPacket(incomingPacket);
}
break;
default:
nodeList->processNodeData(senderSockAddr, incomingPacket);
break;
}
}
}
示例8: getFeatures
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent )
{
mUri = uri;
mWkbType = wkbType;
XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR );
XML_SetUserData( p, this );
XML_SetElementHandler( p, QgsGml::start, QgsGml::end );
XML_SetCharacterDataHandler( p, QgsGml::chars );
//start with empty extent
mExtent.setMinimal();
QNetworkRequest request( mUri );
QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request );
connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) );
connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) );
//find out if there is a QGIS main window. If yes, display a progress dialog
QProgressDialog* progressDialog = 0;
QWidget* mainWindow = qApp->activeWindow();
if ( mainWindow )
{
progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow );
progressDialog->setWindowModality( Qt::ApplicationModal );
connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) );
connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) );
connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) );
progressDialog->show();
}
int atEnd = 0;
while ( !atEnd )
{
if ( mFinished )
{
atEnd = 1;
}
QByteArray readData = reply->readAll();
if ( readData.size() > 0 )
{
XML_Parse( p, readData.constData(), readData.size(), atEnd );
}
QCoreApplication::processEvents();
}
delete reply;
delete progressDialog;
if ( *mWkbType != QGis::WKBNoGeometry )
{
if ( mExtent.isEmpty() )
{
//reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features
calculateExtentFromFeatures();
}
}
XML_ParserFree( p );
if ( extent )
*extent = mExtent;
return 0;
}
示例9: qStreamNtlmBuffer
static void qStreamNtlmBuffer(QDataStream& ds, const QByteArray& s)
{
ds.writeRawData(s.constData(), s.size());
}
示例10: while
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
{
QHash<QByteArray, QByteArray> options;
// parse the challenge
const char *d = challenge.constData();
const char *end = d + challenge.length();
while (d < end) {
while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
++d;
const char *start = d;
while (d < end && *d != '=')
++d;
QByteArray key = QByteArray(start, d - start);
++d;
if (d >= end)
break;
bool quote = (*d == '"');
if (quote)
++d;
if (d >= end)
break;
start = d;
QByteArray value;
while (d < end) {
bool backslash = false;
if (*d == '\\' && d < end - 1) {
++d;
backslash = true;
}
if (!backslash) {
if (quote) {
if (*d == '"')
break;
} else {
if (*d == ',')
break;
}
}
value += *d;
++d;
}
while (d < end && *d != ',')
++d;
++d;
options[key] = value;
}
QByteArray qop = options.value("qop");
if (!qop.isEmpty()) {
QList<QByteArray> qopoptions = qop.split(',');
if (!qopoptions.contains("auth"))
return QHash<QByteArray, QByteArray>();
// #### can't do auth-int currently
// if (qop.contains("auth-int"))
// qop = "auth-int";
// else if (qop.contains("auth"))
// qop = "auth";
// else
// qop = QByteArray();
options["qop"] = "auth";
}
return options;
}
示例11: open
bool BaseTextDocument::open(const QString &fileName)
{
QString title = tr("untitled");
if (!fileName.isEmpty()) {
const QFileInfo fi(fileName);
m_fileName = fi.absoluteFilePath();
QFile file(fileName);
if (!file.exists())
return false;
if (!fi.isReadable())
return false;
if (!fi.isWritable()) {
if (!file.open(QIODevice::ReadOnly))
return false;
} else {
if (!file.open(QIODevice::ReadWrite))
return false;
}
title = fi.fileName();
QByteArray buf = file.readAll();
int bytesRead = buf.size();
QTextCodec *codec = m_codec;
// code taken from qtextstream
if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
|| (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-32");
} else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
|| (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-16");
} else if (!codec) {
codec = QTextCodec::codecForLocale();
}
// end code taken from qtextstream
m_codec = codec;
#if 0 // should work, but does not, Qt bug with "system" codec
QTextDecoder *decoder = m_codec->makeDecoder();
QString text = decoder->toUnicode(buf);
m_hasDecodingError = (decoder->hasFailure());
delete decoder;
#else
QString text = m_codec->toUnicode(buf);
QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
// the minSize trick lets us ignore unicode headers
int minSize = qMin(verifyBuf.size(), buf.size());
m_hasDecodingError = (minSize < buf.size()- 4
|| memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
buf.constData() + buf.size() - minSize, minSize));
#endif
if (m_hasDecodingError) {
int p = buf.indexOf('\n', 16384);
if (p < 0)
m_decodingErrorSample = buf;
else
m_decodingErrorSample = buf.left(p);
} else {
m_decodingErrorSample.clear();
}
int lf = text.indexOf('\n');
if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
m_lineTerminatorMode = CRLFLineTerminator;
} else if (lf >= 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
m_lineTerminatorMode = NativeLineTerminator;
}
m_document->setModified(false);
m_document->setUndoRedoEnabled(false);
if (m_isBinaryData)
m_document->setHtml(tr("<em>Binary data</em>"));
else
m_document->setPlainText(text);
m_document->setUndoRedoEnabled(true);
TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout());
QTC_ASSERT(documentLayout, return true);
documentLayout->lastSaveRevision = 0;
m_document->setModified(false);
emit titleChanged(title);
emit changed();
}
return true;
}
示例12: writeFromBuffer
void Writer::writeFromBuffer(const QByteArray &buffer)
{
int len = protocol::Message::sniffLength(buffer.constData());
Q_ASSERT(len <= buffer.length());
_file->write(buffer.constData(), len);
}
示例13: module
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
Base::PyGILStateLocker lock;
QMap<QString, CallTip> tips;
if (context.isEmpty())
return tips;
try {
QStringList items = context.split(QLatin1Char('.'));
Py::Module module("__main__");
Py::Dict dict = module.getDict();
QString modname = items.front();
items.pop_front();
if (!dict.hasKey(std::string(modname.toLatin1())))
return tips; // unknown object
// get the Python object we need
Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
while (!items.isEmpty()) {
QByteArray name = items.front().toLatin1();
std::string attr = name.constData();
items.pop_front();
if (obj.hasAttr(attr))
obj = obj.getAttr(attr);
else
return tips;
}
// Checks whether the type is a subclass of PyObjectBase because to get the doc string
// of a member we must get it by its type instead of its instance otherwise we get the
// wrong string, namely that of the type of the member.
// Note: 3rd party libraries may use their own type object classes so that we cannot
// reliably use Py::Type. To be on the safe side we should use Py::Object to assign
// the used type object to.
//Py::Object type = obj.type();
Py::Object type(PyObject_Type(obj.ptr()), true);
Py::Object inst = obj; // the object instance
union PyType_Object typeobj = {&Base::PyObjectBase::Type};
union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
// From the template Python object we don't query its type object because there we keep
// a list of additional methods that we won't see otherwise. But to get the correct doc
// strings we query the type's dict in the class itself.
// To see if we have a template Python object we check for the existence of supportedProperties
if (!type.hasAttr("supportedProperties")) {
obj = type;
}
}
else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
obj = type;
}
// If we have an instance of PyObjectBase then determine whether it's valid or not
if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
}
else {
// PyObject_IsInstance might set an exception
PyErr_Clear();
}
Py::List list(PyObject_Dir(obj.ptr()), true);
// If we derive from PropertyContainerPy we can search for the properties in the
// C++ twin class.
union PyType_Object proptypeobj = {&App::PropertyContainerPy::Type};
if (PyObject_IsSubclass(type.ptr(), proptypeobj.o) == 1) {
// These are the attributes of the instance itself which are NOT accessible by
// its type object
extractTipsFromProperties(inst, tips);
}
// If we derive from App::DocumentPy we have direct access to the objects by their internal
// names. So, we add these names to the list, too.
union PyType_Object appdoctypeobj = {&App::DocumentPy::Type};
if (PyObject_IsSubclass(type.ptr(), appdoctypeobj.o) == 1) {
App::DocumentPy* docpy = (App::DocumentPy*)(inst.ptr());
App::Document* document = docpy->getDocumentPtr();
// Make sure that the C++ object is alive
if (document) {
std::vector<App::DocumentObject*> objects = document->getObjects();
Py::List list;
for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
list.append(Py::String((*it)->getNameInDocument()));
extractTipsFromObject(inst, list, tips);
}
}
// If we derive from Gui::DocumentPy we have direct access to the objects by their internal
// names. So, we add these names to the list, too.
union PyType_Object guidoctypeobj = {&Gui::DocumentPy::Type};
if (PyObject_IsSubclass(type.ptr(), guidoctypeobj.o) == 1) {
Gui::DocumentPy* docpy = (Gui::DocumentPy*)(inst.ptr());
if (docpy->getDocumentPtr()) {
App::Document* document = docpy->getDocumentPtr()->getDocument();
// Make sure that the C++ object is alive
if (document) {
std::vector<App::DocumentObject*> objects = document->getObjects();
Py::List list;
//.........这里部分代码省略.........
示例14: s
bool ParamComboBox :: StoreParameterValue ()
{
QVariant v = pcb_combo_box_p -> currentData ();
bool success_flag = false;
switch (bpw_param_p -> pa_type)
{
case PT_LARGE_STRING:
case PT_STRING:
case PT_FILE_TO_READ:
case PT_FILE_TO_WRITE:
case PT_DIRECTORY:
case PT_KEYWORD:
{
QString s (v.toString ());
QByteArray ba = s.toLocal8Bit ();
const char *value_s = ba.constData ();
success_flag = SetParameterValue (bpw_param_p, value_s, true);
qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << value_s;
}
break;
case PT_CHAR:
{
QChar qc = v.toChar ();
char c = qc.toLatin1 ();
success_flag = SetParameterValue (bpw_param_p, &c, true);
qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << c;
}
break;
case PT_BOOLEAN:
{
bool b = v.toBool ();
success_flag = SetParameterValue (bpw_param_p, &b, true);
qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << b;
}
break;
case PT_SIGNED_INT:
case PT_UNSIGNED_INT:
{
bool conv_flag = false;
int i = v.toInt (&conv_flag);
if (conv_flag)
{
success_flag = SetParameterValue (bpw_param_p, &i, true);
qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << i;
}
}
break;
case PT_SIGNED_REAL:
case PT_UNSIGNED_REAL:
{
bool conv_flag = false;
double d = v.toDouble (&conv_flag);
if (conv_flag)
{
success_flag = SetParameterValue (bpw_param_p, &d, true);
qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << d;
}
}
break;
default:
break;
}
return success_flag;
}
示例15: addTTFile
QStringList QWebOSFontDatabase::addTTFile(QWebOSFontDatabase* qwfdb, const QByteArray &fontData, const QByteArray &file, const QStringList &additionalFamilies)
{
if (qwfdb && qwfdb->m_debug)
qDebug("addTTFile(fontData.size() = %d, file = '%s', additionalFamilies = '%s')",
fontData.size(),
qPrintable(file),
qPrintable(additionalFamilies.join(",")));
extern FT_Library qt_getFreetype();
FT_Library library = qt_getFreetype();
int numFaces = 0;
int index = 0;
QStringList families;
FT_Face face;
FT_Error error;
if (!fontData.isEmpty()) {
error = FT_New_Memory_Face(library, (const FT_Byte *)fontData.constData(), fontData.size(), index, &face);
} else {
error = FT_New_Face(library, file.constData(), index, &face);
}
if (error != FT_Err_Ok) {
qDebug() << "FT_New_Face for " << qPrintable(file) << " failed with index" << index << ":" << hex << error;
return families;
}
numFaces = face->num_faces;
if (numFaces > 1) {
qWarning() << "numFaces for " << qPrintable(file) << " is " << numFaces << ", expected just 1";
}
QFont::Weight weight = QFont::Normal;
QFont::Stretch stretch = QFont::Unstretched;
QFont::Style style = QFont::StyleNormal;
if (face->style_flags & FT_STYLE_FLAG_ITALIC)
style = QFont::StyleItalic;
if (face->style_flags & FT_STYLE_FLAG_BOLD)
weight = QFont::Bold;
QSupportedWritingSystems writingSystems;
// detect symbol fonts
for (int i = 0; i < face->num_charmaps; ++i) {
FT_CharMap cm = face->charmaps[i];
if (cm->encoding == ft_encoding_adobe_custom
|| cm->encoding == ft_encoding_symbol) {
writingSystems.setSupported(QFontDatabase::Symbol);
break;
}
}
TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
if (os2) {
quint32 unicodeRange[4] = {
os2->ulUnicodeRange1, os2->ulUnicodeRange2, os2->ulUnicodeRange3, os2->ulUnicodeRange4
};
quint32 codePageRange[2] = {
os2->ulCodePageRange1, os2->ulCodePageRange2
};
writingSystems = determineWritingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
// If the OS2 struct is availabel read the weight from there and convert it
// to a QFont::Weight. This fixes OWEBOS-1866
weight = weightFromInteger(os2->usWeightClass);
stretch = determineStretchFromTrueTypeWidthClass(os2->usWidthClass);
style = determineStyleFromTrueTypeSelection(os2->fsSelection);
}
QString family = QString::fromAscii(face->family_name);
QStringList allFamilies(family);
allFamilies << additionalFamilies;
for (int i = 0; i < allFamilies.size(); ++i) {
FontFile *fontFile = new FontFile;
fontFile->fileName = file;
fontFile->indexValue = index;
fontFile->familyName = allFamilies.at(i);
qDebug("registerFont(\"%s\",\"\",%s,%s,%s,true,true,0,\"%s\",fontFile = {fileName = \"%s\", indexValue = %d, familyName = %s})",
qPrintable(allFamilies.at(i)),
qPrintable(qWeightToQString(weight)),
qPrintable(qStyleToQString(style)),
qPrintable(qStretchToQString(stretch)),
qPrintable(qSupportedWritingSystemsToQString(writingSystems)),
qPrintable(fontFile->fileName),
fontFile->indexValue,
qPrintable(fontFile->familyName));
registerFont(allFamilies.at(i), "", weight, style, stretch, true, true, 0, writingSystems, fontFile);
families.append(family);
}
FT_Done_Face(face);
return families;
}