本文整理汇总了C++中QEventLoop类的典型用法代码示例。如果您正苦于以下问题:C++ QEventLoop类的具体用法?C++ QEventLoop怎么用?C++ QEventLoop使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QEventLoop类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: wait
// --------------------------------------------------------------------------
void wait(int msec)
{
QEventLoop eventLoop;
QTimer::singleShot(msec, &eventLoop, SLOT(quit()));
eventLoop.exec();
}
示例2: connect
/*!
* \brief Waits for response from the server.
* On Linux it is used in a seperate thread, so the main
* thread would not be freezed during the waiting of
* the server repsonse.
*/
void Translator::linuxTranslate(QNetworkRequest &request)
{
QEventLoop loop;
connect(parent->getManager()->get(request), &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
}
示例3: SLOT
void kwp2000::pause()
{
QEventLoop loop;
QTimer::singleShot(900, &loop, SLOT(quit()));
loop.exec();
}
示例4: startEventLoop
void TestAbstractAsyncClient::startEventLoop(const int delay)
{
QEventLoop el;
QTimer::singleShot(delay, &el, SLOT(quit()));
el.exec();
}
示例5: Delay
void Delay()
{
QEventLoop loop;
QTimer::singleShot(1, &loop, SLOT(quit()));
loop.exec();
}
示例6: QDialog
Installer::Installer(QWidget *parent) :
QDialog(parent),
ui(new Ui::Installer)
{
setAttribute(Qt::WA_DeleteOnClose, true);
ui->setupUi(this);
QProgressDialog wait(this);
wait.setLabelText("Checking for new Required Core Tools ...");
wait.show();
if (qnam.networkAccessible() != QNetworkAccessManager::Accessible) {
wait.hide();
QMessageBox::critical(this, "Network Inaccessible", "Can't check for updates as you appear to be offline.");
return;
}
QSettings conf;
QWidget *w = new QWidget;
QGridLayout *g = new QGridLayout;
QPushButton *b = 0;
#if defined(Q_OS_WIN)
#define OS_PATH "win32"
#elif defined(Q_OS_MAC)
#define OS_PATH "osx"
#elif defined(Q_OS_LINUX)
#define OS_PATH "osx"
#else
#error "Not yet specialized for other OSs"
#endif
int row = 0;
g->addWidget(new QLabel("Name"), row, 0, 1, 1, Qt::AlignLeft);
g->addWidget(new QLabel("Size"), row, 1, 1, 1, Qt::AlignHCenter);
g->addWidget(new QLabel("Action"), row, 2, 1, 1, Qt::AlignRight);
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
{
reply = qnam.head(QNetworkRequest(QUrl("http://apertium.projectjj.com/" OS_PATH "/nightly/apertium-all-dev.7z")));
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QString lm = reply->rawHeader("Last-Modified");
QString cl = reply->rawHeader("Content-Length");
QString label("Install");
if (conf.contains("apertium-all-dev")) {
label = "Reinstall";
if (conf.value("apertium-all-dev").toString() != lm) {
label = "Update";
}
}
++row;
g->addWidget(new QLabel("Required Core Tools"), row, 0, 1, 1, Qt::AlignLeft);
g->addWidget(new QLabel(formatBytes(cl.toUInt())), row, 1, 1, 1, Qt::AlignRight);
g->addWidget(b = new QPushButton(label), row, 2, 1, 1, Qt::AlignRight);
b->setProperty("name", "apertium-all-dev");
b->setProperty("url", QString("http://apertium.projectjj.com/" OS_PATH "/nightly/apertium-all-dev.7z"));
b->setProperty("bsize", cl);
b->setProperty("lm", lm);
connect(b, SIGNAL(clicked()), this, SLOT(installpkg()));
}
#endif
{
wait.setLabelText("Checking for new language pairs ...");
reply = qnam.get(QNetworkRequest(QUrl("http://apertium.projectjj.com/" OS_PATH "/nightly/data.php")));
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QString body = reply->readAll();
QRegularExpression rx("<tr><td>(apertium-\\w+-\\w+)</td><td>[^<]+</td><td>(\\d+)</td><td>([^<]+)</td>.*?</tr>");
QRegularExpressionMatchIterator it = rx.globalMatch(body);
while (it.hasNext()) {
QRegularExpressionMatch m = it.next();
QString name = m.captured(1);
QString label("Install");
if (conf.contains(name)) {
label = "Reinstall";
if (conf.value(name).toString() != m.captured(3)) {
label = "Update";
}
}
++row;
g->addWidget(new QLabel(name), row, 0, 1, 1, Qt::AlignLeft);
g->addWidget(new QLabel(formatBytes(m.captured(2).toUInt())), row, 1, 1, 1, Qt::AlignRight);
g->addWidget(b = new QPushButton(label), row, 2, 1, 1, Qt::AlignRight);
b->setProperty("name", name);
b->setProperty("url", QString("http://apertium.projectjj.com/" OS_PATH "/nightly/data.php?deb=")+name);
b->setProperty("bsize", m.captured(2));
b->setProperty("lm", m.captured(3));
connect(b, SIGNAL(clicked()), this, SLOT(installpkg()));
}
}
//.........这里部分代码省略.........
示例7: loadNext
int User::loadNext() {
if (queue.empty()) return 1;
if (this->cancel) return 1;
QMap<Anime *, bool> data = queue.front();
queue.pop();
Anime *anime = data.keys().first();
bool download_cover = data.values().first();
QString ID = anime->getID();
QUrl ID_URL = API::sharedAPI()->sharedAniListAPI()->API_ANIME(ID);
QJsonObject result =
API::sharedAPI()->sharedAniListAPI()->get(ID_URL).object();
anime->setCoverURL(QUrl(result.value("image_url_lge").toString()));
if (download_cover) {
QEventLoop evt;
connect(anime, SIGNAL(new_image()), &evt, SLOT(quit()));
anime->downloadCover();
evt.exec();
}
QString description = result.value("description").toString();
anime->setDuration(result.value("duration").toInt());
anime->setSynopsis(description);
anime->setRomajiTitle(result.value("title_romaji").toString());
anime->setJapaneseTitle(result.value("title_japanese").toString());
anime->setEnglishTitle(result.value("title_english").toString());
anime->setType(result.value("type").toString());
anime->setAiringStatus(result.value("airing_status").toString());
anime->setEpisodeCount(result.value("total_episodes").toInt());
anime->setAverageScore(result.value("average_score").toString());
anime->setTitle(result.value(title_language).toString());
if (anime->getAiringStatus() == "currently airing") {
QJsonObject airing = result.value("airing").toObject();
anime->setNextEpisode(airing.value("next_episode").toInt());
anime->setCountdown(airing.value("countdown").toInt());
if (anime->getCountdown() > 0) {
anime->setAiringSchedule(true);
} else {
anime->setAiringSchedule(false);
}
}
QJsonArray synonyms = result.value("synonyms").toArray();
for (int j = 0; j < synonyms.count(); j++) {
anime->addSynonym(synonyms.at(j).toString());
}
anime->finishReload();
qDebug() << "Loaded extra data for anime" << anime->getTitle();
db->saveAnime(anime);
if (!queue.empty()) {
async_registry.append(QtConcurrent::run([&, this]() { // NOLINT
loadNext();
return 1;
}));
}
return 1;
}
示例8: abort
bool QgsWfsRequest::sendGET( const QUrl &url, bool synchronous, bool forceRefresh, bool cache )
{
abort(); // cancel previous
mIsAborted = false;
mTimedout = false;
mGotNonEmptyResponse = false;
mErrorMessage.clear();
mErrorCode = QgsWfsRequest::NoError;
mForceRefresh = forceRefresh;
mResponse.clear();
QUrl modifiedUrl( url );
// Specific code for testing
if ( modifiedUrl.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) )
{
// Just for testing with local files instead of http:// resources
QString modifiedUrlString = modifiedUrl.toString();
// Qt5 does URL encoding from some reason (of the FILTER parameter for example)
modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
QgsDebugMsg( QString( "Get %1" ).arg( modifiedUrlString ) );
modifiedUrlString = modifiedUrlString.mid( QStringLiteral( "http://" ).size() );
QString args = modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) );
if ( modifiedUrlString.size() > 256 )
{
args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
}
else
{
args.replace( QLatin1String( "?" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "&" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "<" ), QLatin1String( "_" ) );
args.replace( QLatin1String( ">" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "'" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "\"" ), QLatin1String( "_" ) );
args.replace( QLatin1String( " " ), QLatin1String( "_" ) );
args.replace( QLatin1String( ":" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "/" ), QLatin1String( "_" ) );
args.replace( QLatin1String( "\n" ), QLatin1String( "_" ) );
}
#ifdef Q_OS_WIN
// Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
// so we must restore it
if ( modifiedUrlString[1] == '/' )
{
modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
}
#endif
modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
QgsDebugMsg( QStringLiteral( "Get %1 (after laundering)" ).arg( modifiedUrlString ) );
modifiedUrl = QUrl::fromLocalFile( modifiedUrlString );
}
QgsDebugMsgLevel( QStringLiteral( "Calling: %1" ).arg( modifiedUrl.toDisplayString( ) ), 4 );
QNetworkRequest request( modifiedUrl );
if ( !mUri.auth().setAuthorization( request ) )
{
mErrorCode = QgsWfsRequest::NetworkError;
mErrorMessage = errorMessageFailedAuth();
QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) );
return false;
}
if ( cache )
{
request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, forceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache );
request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );
}
mReply = QgsNetworkAccessManager::instance()->get( request );
if ( !mUri.auth().setAuthorizationReply( mReply ) )
{
mErrorCode = QgsWfsRequest::NetworkError;
mErrorMessage = errorMessageFailedAuth();
QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) );
return false;
}
connect( mReply, &QNetworkReply::finished, this, &QgsWfsRequest::replyFinished );
connect( mReply, &QNetworkReply::downloadProgress, this, &QgsWfsRequest::replyProgress );
if ( !synchronous )
return true;
QEventLoop loop;
connect( this, &QgsWfsRequest::downloadFinished, &loop, &QEventLoop::quit );
loop.exec( QEventLoop::ExcludeUserInputEvents );
return mErrorMessage.isEmpty();
}
示例9: QUrl
void Agent::run() {
ThreadedAssignment::commonInit(AGENT_LOGGING_NAME, NodeType::Agent);
NodeList* nodeList = NodeList::getInstance();
nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet()
<< NodeType::AudioMixer
<< NodeType::AvatarMixer
<< NodeType::VoxelServer
<< NodeType::ParticleServer
<< NodeType::ModelServer
);
// figure out the URL for the script for this agent assignment
QUrl scriptURL;
if (_payload.isEmpty()) {
scriptURL = QUrl(QString("http://%1:%2/assignment/%3")
.arg(NodeList::getInstance()->getDomainHandler().getIP().toString())
.arg(DOMAIN_SERVER_HTTP_PORT)
.arg(uuidStringWithoutCurlyBraces(_uuid)));
} else {
scriptURL = QUrl(_payload);
}
NetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
QNetworkReply *reply = networkAccessManager.get(QNetworkRequest(scriptURL));
QNetworkDiskCache* cache = new QNetworkDiskCache();
QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "agentCache");
networkAccessManager.setCache(cache);
qDebug() << "Downloading script at" << scriptURL.toString();
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QString scriptContents(reply->readAll());
qDebug() << "Downloaded script:" << scriptContents;
// setup an Avatar for the script to use
ScriptableAvatar scriptedAvatar(&_scriptEngine);
scriptedAvatar.setForceFaceshiftConnected(true);
// call model URL setters with empty URLs so our avatar, if user, will have the default models
scriptedAvatar.setFaceModelURL(QUrl());
scriptedAvatar.setSkeletonModelURL(QUrl());
// give this AvatarData object to the script engine
_scriptEngine.setAvatarData(&scriptedAvatar, "Avatar");
_scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarList");
// register ourselves to the script engine
_scriptEngine.registerGlobalObject("Agent", this);
_scriptEngine.init(); // must be done before we set up the viewers
_scriptEngine.registerGlobalObject("VoxelViewer", &_voxelViewer);
// connect the VoxelViewer and the VoxelScriptingInterface to each other
JurisdictionListener* voxelJL = _scriptEngine.getVoxelsScriptingInterface()->getJurisdictionListener();
_voxelViewer.setJurisdictionListener(voxelJL);
_voxelViewer.init();
_scriptEngine.getVoxelsScriptingInterface()->setVoxelTree(_voxelViewer.getTree());
_scriptEngine.registerGlobalObject("ParticleViewer", &_particleViewer);
JurisdictionListener* particleJL = _scriptEngine.getParticlesScriptingInterface()->getJurisdictionListener();
_particleViewer.setJurisdictionListener(particleJL);
_particleViewer.init();
_scriptEngine.getParticlesScriptingInterface()->setParticleTree(_particleViewer.getTree());
_scriptEngine.registerGlobalObject("ModelViewer", &_modelViewer);
JurisdictionListener* modelJL = _scriptEngine.getModelsScriptingInterface()->getJurisdictionListener();
_modelViewer.setJurisdictionListener(modelJL);
_modelViewer.init();
_scriptEngine.getModelsScriptingInterface()->setModelTree(_modelViewer.getTree());
_scriptEngine.setScriptContents(scriptContents);
_scriptEngine.run();
setFinished(true);
}
示例10: defaultSize
void MainWindow::loadSettings()
{
mainLog.Log("Loading settings...");
QSettings settings;
if(settings.allKeys().size() == 0)
{
mainLog.Log("Settings is empty. Default values will be used.");
}
else mainLog.Log("Loading settings from %s.", settings.fileName().toLocal8Bit().data());
QPoint defaultPosition;
QSize defaultSize(800,600);
if(!settings.contains("MainWindow/size") || !settings.contains("MainWindow/pos"))
{
int frameWidth = 0;
int frameTop = 0;
int frameBottom = 0;
bool screenHack = true; //If we want to get frame geometry (which is apparently a pain in qt).
if(screenHack)
{
//The following from a post on stackoverflow by TonyK
// BIG PAIN: We want to get the dialog box to caluclate its own size. But there is
// no simple way to do this. The following seems to work, but only if processEvents
// is called at least twice. God knows why:
setAttribute (Qt::WA_DontShowOnScreen, true) ; // Prevent screen flicker
show() ;
QEventLoop EventLoop (this) ;
for (int i = 0 ; i < 10 ; i++)
if (!EventLoop.processEvents()) break ;
hide() ;
setAttribute (Qt::WA_DontShowOnScreen, false) ;
//End code section from TonyK
frameWidth = frameGeometry().width()-geometry().width();
frameTop = abs(geometry().top()-frameGeometry().top());
frameBottom = abs(frameGeometry().bottom()-geometry().bottom());
}
//Ensure sane positioning for first run (i.e. not split across multiple monitors
QDesktopWidget* desk = QApplication::desktop();
int usedScreen = 0;
const QRect available = desk->availableGeometry(usedScreen);
if((available.x()+available.width())/2 >= defaultSize.width()/2+frameWidth/2)
{
defaultPosition.setX((available.x()+available.width())/2-(defaultSize.width()/2+frameWidth/2));
}
else
{
defaultPosition.setX(available.x());
defaultSize.setWidth(available.width()-frameWidth);
}
if((available.y()+available.height())/2 >= defaultSize.height()/2 + (frameTop+frameBottom)/2)
{
defaultPosition.setY((available.y()+available.height())/2-defaultSize.height()/2);
}
else
{
defaultPosition.setY(available.y());
defaultSize.setHeight(available.height()-(frameTop+frameBottom));
}
mainLog.Log("Positioning window at (%d, %d) with size (%d, %d) on screen %d/%d",defaultPosition.x(),defaultPosition.y(),defaultSize.width(),defaultSize.height(),usedScreen,desk->screenCount());
}
mainLog.setLogPriority(settings.value("LoggingLevels/mainLog",DEFAULT_PRIORITY).toInt());
levelLog.setLogPriority(settings.value("LoggingLevels/levelLog",DEFAULT_PRIORITY).toInt());
int levelPriorities[NUMBER_OF_BLOCKS];
levelPriorities[BLOCK_TEXTURES] = settings.value("LoggingLevels/blockTextures",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_MODELS] = settings.value("LoggingLevels/blockModels",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_WORLD] = settings.value("LoggingLevels/blockWorld",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_RANDOM_MODEL_PLACEMENT] = settings.value("LoggingLevels/blockRandomModelPlacement",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_TEXTURE_DEFINITIONS] = settings.value("LoggingLevels/blockTextureDefinitions",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_ROAD_TABLE] = settings.value("LoggingLevels/blockRoadTable",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_ROAD_CONNECTIONS] = settings.value("LoggingLevels/blockRoadConnections",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_INTERSECTIONS] = settings.value("LoggingLevels/blockIntersections",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_HEIGHTMAP_TILES] = settings.value("LoggingLevels/blockHeightmapTiles",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_HEIGHTMAP] = settings.value("LoggingLevels/blockHeightmap",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_MODEL_NAMES] = settings.value("LoggingLevels/blockModelNames",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_EVENT_MODELS] = settings.value("LoggingLevels/blockEventModels",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_VISIBILITY] = settings.value("LoggingLevels/blockVisibility",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_SECTOR_TEXTURE_USAGE] = settings.value("LoggingLevels/blockSectorTextureUsage",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_ROAD_SECTIONS] = settings.value("LoggingLevels/blockRoadSections",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_INTERSECTION_POSITIONS] = settings.value("LoggingLevels/blockIntersectionPositions",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_LAMPS] = settings.value("LoggingLevels/blockLamps",levelLog.getLogPriority()).toInt();
levelPriorities[BLOCK_CHAIR_PLACEMENT] = settings.value("LoggingLevels/blockChairPlacement",levelLog.getLogPriority()).toInt();
level.setLogPriorities(levelPriorities);
resize(settings.value("MainWindow/size",defaultSize).toSize());
move(settings.value("MainWindow/pos", defaultPosition).toPoint());
if(settings.value("MainWindow/maximized",false).toBool())
showMaximized();
else showNormal();
show();
customLevelDialog->setLastDirectory(settings.value("directories/lastOpenFileDir","C:\\Program Files\\GT Interactive\\Driver\\Levels").toString());
//.........这里部分代码省略.........
示例11: Q_UNUSED
void QgsComposerLabel::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
Q_UNUSED( itemStyle );
Q_UNUSED( pWidget );
if ( !painter )
{
return;
}
drawBackground( painter );
painter->save();
double penWidth = pen().widthF();
QRectF painterRect( penWidth + mMargin, penWidth + mMargin, rect().width() - 2 * penWidth - 2 * mMargin, rect().height() - 2 * penWidth - 2 * mMargin );
QString textToDraw = displayText();
if ( mHtmlState )
{
painter->scale( 1.0 / mHtmlUnitsToMM / 10.0, 1.0 / mHtmlUnitsToMM / 10.0 );
QWebPage *webPage = new QWebPage();
webPage->setNetworkAccessManager( QgsNetworkAccessManager::instance() );
//Setup event loop and timeout for rendering html
QEventLoop loop;
QTimer timeoutTimer;
timeoutTimer.setSingleShot( true );
//This makes the background transparent. Found on http://blog.qt.digia.com/blog/2009/06/30/transparent-qwebview-or-qwebpage/
QPalette palette = webPage->palette();
palette.setBrush( QPalette::Base, Qt::transparent );
webPage->setPalette( palette );
//webPage->setAttribute(Qt::WA_OpaquePaintEvent, false); //this does not compile, why ?
webPage->setViewportSize( QSize( painterRect.width() * mHtmlUnitsToMM * 10.0, painterRect.height() * mHtmlUnitsToMM * 10.0 ) );
webPage->mainFrame()->setZoomFactor( 10.0 );
webPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
webPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
// QGIS segfaults when rendering web page while in composer if html
// contains images. So if we are not printing the composition, then
// disable image loading
if ( mComposition->plotStyle() != QgsComposition::Print &&
mComposition->plotStyle() != QgsComposition::Postscript )
{
webPage->settings()->setAttribute( QWebSettings::AutoLoadImages, false );
}
//Connect timeout and webpage loadFinished signals to loop
connect( &timeoutTimer, SIGNAL( timeout() ), &loop, SLOT( quit() ) );
connect( webPage, SIGNAL( loadFinished( bool ) ), &loop, SLOT( quit() ) );
//mHtmlLoaded tracks whether the QWebPage has completed loading
//its html contents, set it initially to false. The loadingHtmlFinished slot will
//set this to true after html is loaded.
mHtmlLoaded = false;
connect( webPage, SIGNAL( loadFinished( bool ) ), SLOT( loadingHtmlFinished( bool ) ) );
webPage->mainFrame()->setHtml( textToDraw );
//For very basic html labels with no external assets, the html load will already be
//complete before we even get a chance to start the QEventLoop. Make sure we check
//this before starting the loop
if ( !mHtmlLoaded )
{
// Start a 20 second timeout in case html loading will never complete
timeoutTimer.start( 20000 );
// Pause until html is loaded
loop.exec();
}
webPage->mainFrame()->render( painter );//DELETE WEBPAGE ?
}
else
{
示例12: sleep
void qtools::sleep(int msec)
{
QEventLoop loop;
QTimer::singleShot(1000,&loop,SLOT(quit()));
loop.exec();
}
示例13: LOG_ERROR
void CHttpThread::sendHttp(const CProtocol& protocol)
{
//LOG_PROTOCOL(protocol);
QByteArray postData;
// konwertuj protokol do postaci binarnej tablicy QByteArray
if (!convertToBinary(postData, protocol)){
// nieprawidlowy format protokolu
LOG_ERROR("Sending protocol error. idPackage:", protocol.getIdPackage());
DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::OUTPUT_PROTOCOL_FORMAT_ERROR));
resultsQueue.push(res);
}
else
{
//convertToProtocolDebug(postData);
uint16_t crc = NUtil::CCryptography::crc16(postData.constData(), postData.size());
postData.replace(postData.size() - sizeof(crc), sizeof(crc), reinterpret_cast<char*>(&crc), sizeof(crc));
// tworzy tymczasowa petle komunikatow
QEventLoop eventLoop;
// dla sygnalu QNetworkAccessManager::finished wywolaj QEventLoop::quit
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// HTTP
const std::string url = NEngine::CConfigurationFactory::getInstance()->getServerUrl();
QUrl qUrl(url.c_str());
QNetworkRequest req(qUrl);
// typ MIME
req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
// wyslij post'a
std::shared_ptr<QNetworkReply> reply(mgr.post(req, postData));
eventLoop.exec(); // czekaj QEventLoop::quit (czyli QNetworkAccessManager::finished)
if (reply->error() == QNetworkReply::NoError) {
//success
LOG_DEBUG("Protocol has been sent successfully. idPackage:", protocol.getIdPackage());
CByteWrapper wrapper(reply->readAll());
// wyslanie potwierdzenia zmiany konfiguracji - jesli zmiana odbyla sie bez problemow nie zwraca danych
if (wrapper.getSize() > 0)
{
if (!wrapper.isCRCValid())
{
LOG_ERROR("Received protocol error - CRC. idPackage:", protocol.getIdPackage());
DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CRC_ERROR));
resultsQueue.push(res);
}
else
{
std::shared_ptr<CProtocol> responseProtocol =
convertToProtocol(wrapper);
// przekonwertuj do struktury
if (!responseProtocol)
{
// blad struktury protokolu
LOG_ERROR("Received protocol error. idPackage:", protocol.getIdPackage());
DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::INPUT_PROTOCOL_FORMAT_ERROR));
resultsQueue.push(res);
}
else
{
LOG_DEBUG("Protocol has been received successfully. idPackage:", responseProtocol->getIdPackage());
DConnectionResult res(new CConnectionResult(protocol, responseProtocol, EConnectionStatus::NONE));
resultsQueue.push(res);
}
}
}
}
else {
LOG_ERROR("Protocol sending error. idPackage:",
protocol.getIdPackage(), ". Error: ", reply->errorString().toStdString());
DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CONNECTION_ERROR));
resultsQueue.push(res);
}
}
}
示例14: QFETCH
void TestQGeoPositionInfoSource::lastKnownPosition()
{
CHECK_SOURCE_VALID;
QFETCH(int, positioningMethod);
QFETCH(bool, lastKnownPositionArgument);
QFETCH(bool, positionValid);
#if defined(Q_OS_SYMBIAN)
QSKIP("Real GPS not suitable for autotesting, skipping the test.", SkipAll);
#endif
QGeoPositionInfoSource::PositioningMethods method
= static_cast<QGeoPositionInfoSource::PositioningMethods>(positioningMethod);
if ((m_source->supportedPositioningMethods() & method) == 0)
QSKIP("Not a supported positioning method for this position source", SkipSingle);
m_source->setPreferredPositioningMethods(method);
QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
QSignalSpy timeout(m_source, SIGNAL(updateTimeout()));
int time_out = 7000;
m_source->setUpdateInterval(time_out);
m_source->startUpdates();
// Use QEventLoop instead of qWait() to ensure we stop as soon as a
// position is emitted (otherwise the lastKnownPosition() may have
// changed by the time it is checked)
QEventLoop loop;
QTimer timer;
timer.setInterval(9500);
connect(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)),
&loop, SLOT(quit()));
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
timer.start();
loop.exec();
EXPECT_FAIL_WINCE_SEE_MOBILITY_337_ABORT;
QVERIFY((spy.count() > 0) && (timeout.count() == 0));
QList<QVariant> list = spy.takeFirst();
QGeoPositionInfo info;
info = list.at(0).value<QGeoPositionInfo>();
QGeoPositionInfo lastPositioninfo;
lastPositioninfo = m_source->lastKnownPosition(lastKnownPositionArgument);
QCOMPARE(lastPositioninfo.isValid(), positionValid);
if (positionValid) {
QCOMPARE(info.coordinate(), lastPositioninfo.coordinate());
QCOMPARE(info.timestamp(), lastPositioninfo.timestamp());
QCOMPARE(info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy),
lastPositioninfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy));
if (info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) {
bool isNaN1 = qIsNaN(info.attribute(QGeoPositionInfo::HorizontalAccuracy));
bool isNaN2 = qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy));
QCOMPARE(isNaN1, isNaN2);
if (!isNaN1) {
QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::HorizontalAccuracy),
lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy)), TRUE);
}
}
QCOMPARE(info.hasAttribute(QGeoPositionInfo::VerticalAccuracy),
lastPositioninfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy));
if (info.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) {
bool isNaN1 = qIsNaN(info.attribute(QGeoPositionInfo::VerticalAccuracy));
bool isNaN2 = qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy));
QCOMPARE(isNaN1, isNaN2);
if (!isNaN1) {
QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::VerticalAccuracy),
lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy)), TRUE);
}
}
}
m_source->stopUpdates();
}
示例15: append
void MapQuestRunner::retrieveRoute( const RouteRequest *route )
{
if ( route->size() < 2 ) {
return;
}
QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["mapquest"];
if ( settings.value( "appKey" ).toString().isEmpty() )
{
return;
}
QString url = "http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0";
GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;
append( &url, "from", QString::number( route->source().latitude( degree ), 'f', 6 ) + ',' + QString::number( route->source().longitude( degree ), 'f', 6 ) );
for ( int i=1; i<route->size(); ++i ) {
append( &url, "to", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + ',' + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );
}
QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == MarbleLocale::MetricSystem ? "k" : "m";
append( &url, "units", unit );
if ( settings["noMotorways"].toInt() ) {
append( &url, "avoids", "Limited Access" );
}
if ( settings["noTollroads"].toInt() ) {
append( &url, "avoids", "Toll road" );
}
if ( settings["noFerries"].toInt() ) {
append( &url, "avoids", "Ferry" );
}
if ( !settings["preference"].toString().isEmpty() ) {
append( &url, "routeType", settings["preference"].toString() );
}
if ( !settings["ascending"].toString().isEmpty() && !settings["descending"].toString().isEmpty() ) {
if ( settings["ascending"].toString() == "AVOID_UP_HILL"
&& settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
append( &url, "roadGradeStrategy", "AVOID_ALL_HILLS" );
}
else if ( settings["ascending"].toString() == "FAVOR_UP_HILL"
&& settings["descending"].toString() == "FAVOR_DOWN_HILL" ) {
append( &url, "roadGradeStrategy", "FAVOR_ALL_HILLS" );
}
else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY"
&& settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
append( &url, "roadGradeStrategy", "DEFAULT_STRATEGY" );
}
else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY" ) {
append( &url, "roadGradeStrategy", settings["descending"].toString() );
}
else if ( settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
append( &url, "roadGradeStrategy", settings["ascending"].toString() );
}
else if ( settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
append( &url, "roadGradeStrategy", settings["descending"].toString() );
}
else if ( settings["ascending"].toString() == "AVOID_UP_HILL" ) {
append( &url, "roadGradeStrategy", settings["ascending"].toString() );
}
}
QUrl qurl(url);
// FIXME: verify that this works with special characters.
#if QT_VERSION >= 0x050000
QUrlQuery urlQuery;
urlQuery.addQueryItem( "key", settings.value( "appKey" ).toByteArray() );
qurl.setQuery(urlQuery);
#else
qurl.addEncodedQueryItem( "key", settings.value( "appKey" ).toByteArray() );
#endif
m_request.setUrl( qurl );
m_request.setRawHeader( "User-Agent", HttpDownloadManager::userAgent( "Browser", "MapQuestRunner" ) );
QEventLoop eventLoop;
QTimer timer;
timer.setSingleShot( true );
timer.setInterval( 15000 );
connect( &timer, SIGNAL(timeout()),
&eventLoop, SLOT(quit()));
connect( this, SIGNAL(routeCalculated(GeoDataDocument*)),
&eventLoop, SLOT(quit()) );
// @todo FIXME Must currently be done in the main thread, see bug 257376
QTimer::singleShot( 0, this, SLOT(get()) );
timer.start();
eventLoop.exec();
}