本文整理汇总了C++中QMultiMap::constEnd方法的典型用法代码示例。如果您正苦于以下问题:C++ QMultiMap::constEnd方法的具体用法?C++ QMultiMap::constEnd怎么用?C++ QMultiMap::constEnd使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QMultiMap
的用法示例。
在下文中一共展示了QMultiMap::constEnd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: addTopologicalPoints
int QgsVectorLayerEditUtils::addTopologicalPoints( const QgsPoint& p )
{
if ( !L->hasGeometryType() )
return 1;
QMultiMap<double, QgsSnappingResult> snapResults; //results from the snapper object
//we also need to snap to vertex to make sure the vertex does not already exist in this geometry
QMultiMap<double, QgsSnappingResult> vertexSnapResults;
QList<QgsSnappingResult> filteredSnapResults; //we filter out the results that are on existing vertices
//work with a tolerance because coordinate projection may introduce some rounding
double threshold = 0.0000001;
if ( L->crs().mapUnits() == QGis::Meters )
{
threshold = 0.001;
}
else if ( L->crs().mapUnits() == QGis::Feet )
{
threshold = 0.0001;
}
if ( L->snapWithContext( p, threshold, snapResults, QgsSnapper::SnapToSegment ) != 0 )
{
return 2;
}
QMultiMap<double, QgsSnappingResult>::const_iterator snap_it = snapResults.constBegin();
QMultiMap<double, QgsSnappingResult>::const_iterator vertex_snap_it;
for ( ; snap_it != snapResults.constEnd(); ++snap_it )
{
//test if p is already a vertex of this geometry. If yes, don't insert it
bool vertexAlreadyExists = false;
if ( L->snapWithContext( p, threshold, vertexSnapResults, QgsSnapper::SnapToVertex ) != 0 )
{
continue;
}
vertex_snap_it = vertexSnapResults.constBegin();
for ( ; vertex_snap_it != vertexSnapResults.constEnd(); ++vertex_snap_it )
{
if ( snap_it.value().snappedAtGeometry == vertex_snap_it.value().snappedAtGeometry )
{
vertexAlreadyExists = true;
}
}
if ( !vertexAlreadyExists )
{
filteredSnapResults.push_back( *snap_it );
}
}
insertSegmentVerticesForSnap( filteredSnapResults );
return 0;
}
示例2: if
QVariantMap MediaPlayer2Player::Metadata() const
{
QVariantMap metaData;
switch (Dragon::engine()->mediaSourceType()) {
case Phonon::MediaSource::Invalid:
case Phonon::MediaSource::Empty:
break;
default:
metaData["mpris:trackid"] = QVariant::fromValue<QDBusObjectPath>(QDBusObjectPath(makeTrackId(Dragon::engine()->urlOrDisc()).constData()));
metaData["mpris:length"] = Dragon::engine()->length() * 1000;
metaData["xesam:url"] = Dragon::engine()->urlOrDisc();
}
QMultiMap<QString, QString> phononMetaData = Dragon::engine()->metaData();
QMultiMap<QString, QString>::const_iterator i = phononMetaData.constBegin();
while (i != phononMetaData.constEnd()) {
if (i.key() == "ALBUM" || i.key() == "TITLE")
metaData["xesam:" + i.key().toLower()] = i.value();
else if (i.key() == "ARTIST" || i.key() == "GENRE")
metaData["xesam:" + i.key().toLower()] = QStringList(i.value());
++i;
}
return metaData;
}
示例3: debugMediaObject
static QByteArray debugMediaObject(WebCore::MediaPlayerPrivate* mediaPlayer, const MediaObject& mediaObject)
{
QByteArray byteArray;
QTextStream stream(&byteArray);
const QMetaObject* metaObj = mediaPlayer->metaObject();
QMetaEnum phononStates = metaObj->enumerator(metaObj->indexOfEnumerator("PhononState"));
stream << "debugMediaObject -> Phonon::MediaObject(";
stream << "State: " << phononStates.valueToKey(mediaObject.state());
stream << " | Current time: " << mediaObject.currentTime();
stream << " | Remaining time: " << mediaObject.remainingTime();
stream << " | Total time: " << mediaObject.totalTime();
stream << " | Meta-data: ";
QMultiMap<QString, QString> map = mediaObject.metaData();
for (QMap<QString, QString>::const_iterator it = map.constBegin();
it != map.constEnd(); ++it) {
stream << "(" << it.key() << ", " << it.value() << ")";
}
stream << " | Has video: " << mediaObject.hasVideo();
stream << " | Is seekable: " << mediaObject.isSeekable();
stream << ")";
stream.flush();
return byteArray;
}
示例4: GetMetadata
QVariantMap TrackListDBusHandler::GetMetadata(int position)
{
QVariantMap ret;
if (position < 0 || position > m_tracks.size()-1) {
return ret;
}
//FIXME: ugly and slow
Phonon::MediaObject mediaObject;
mediaObject.setCurrentSource(m_tracks[position]);
QMultiMap<QString, QString> stringMap = mediaObject.metaData();
QMultiMap<QString, QString>::const_iterator i = stringMap.constBegin();
while (i != stringMap.constEnd()) {
bool number = false;
int value = i.value().toInt(&number);
//tracknumber always string, according to MPRIS spec
if (number && (i.key().toLower() != "tracknumber")) {
ret[i.key().toLower()] = value;
} else {
ret[i.key().toLower()] = QVariant(i.value());
}
++i;
}
ret["time"] = mediaObject.totalTime()/1000;
ret["location"] = mediaObject.currentSource().url().toString();
return ret;
}
示例5: fillFilePathsRecursive
static void fillFilePathsRecursive(const QDir& dir, QMultiMap<QByteArray, QByteArray>& sourceFilePaths)
{
QStringList subDirs(dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable));
int i=subDirs.size();
while(--i>=0)
fillFilePathsRecursive(QDir(dir.filePath(subDirs.at(i))),sourceFilePaths);
static QStringList filters = QStringList(QStringLiteral("*.cpp"))
<<QStringLiteral("*.c")
<<QStringLiteral("*.cc")
<<QStringLiteral("*.mm")
<<QStringLiteral("*.ui")
<<QStringLiteral("*rc");
QStringList files(dir.entryList(filters, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable));
i=files.size();
QByteArray absDirPath=dir.absolutePath().toUtf8(); absDirPath.squeeze();
while(--i>=0)
{
//qDebug()<<files.at(i)<<absDirPath;
QByteArray fn=files.at(i).toUtf8(); fn.squeeze();
auto it=sourceFilePaths.constFind(fn);
if (it!=sourceFilePaths.constEnd())
sourceFilePaths.insert(it.key(), absDirPath); //avoid having identical qbytearray objects to save memory
else
sourceFilePaths.insert(fn, absDirPath);
}
}
示例6: generateSignature
/*!
\internal
Generates the OAuth signature.
\see http://oauth.net/core/1.0a/#signing_process
*/
QString Token::generateSignature(const QUrl& requestUrl, const QMultiMap<QString, QString>& requestParameters, HttpMethod method) const
{
QString key = encode(d->consumerSecret) + "&" + encode(d->oauthTokenSecret);
QString baseString;
switch (method) {
case HttpGet: baseString = "GET&"; break;
case HttpPost: baseString = "POST&"; break;
case HttpPut: baseString = "PUT&"; break;
case HttpDelete: baseString = "DELETE&"; break;
case HttpHead: baseString = "HEAD&"; break;
}
baseString += encode(requestUrl.toString(QUrl::RemoveQuery)) + "&";
// encode and concatenate the parameters into a string
QStringList params;
QMap<QString, QString>::const_iterator p = requestParameters.constBegin();
while (p != requestParameters.constEnd()) {
params << QString("%1=%2").arg(encode(p.key())).arg(encode(p.value()));
++p;
}
qSort(params);
baseString += encode(params.join("&"));
// Ok, we have the normalized base string and the key, calculate the HMAC-SHA1 signature
if(tokenService() == "dbox")
return plaintext(baseString, key);
else
return hmac_sha1(baseString, key);
}
示例7: expire
/*!
Cleans the cache so that its size is under the maximum cache size.
Returns the current size of the cache.
When the current size of the cache is greater than the maximumCacheSize()
older cache files are removed until the total size is less then 90% of
maximumCacheSize() starting with the oldest ones first using the file
creation date to determine how old a cache file is.
Subclasses can reimplement this function to change the order that cache
files are removed taking into account information in the application
knows about that QNetworkDiskCache does not, for example the number of times
a cache is accessed.
Note: cacheSize() calls expire if the current cache size is unknown.
\sa maximumCacheSize(), fileMetaData()
*/
qint64 QNetworkDiskCache::expire()
{
Q_D(QNetworkDiskCache);
if (d->currentCacheSize >= 0 && d->currentCacheSize < maximumCacheSize())
return d->currentCacheSize;
if (cacheDirectory().isEmpty()) {
qWarning() << "QNetworkDiskCache::expire() The cache directory is not set";
return 0;
}
// close file handle to prevent "in use" error when QFile::remove() is called
d->lastItem.reset();
QDir::Filters filters = QDir::AllDirs | QDir:: Files | QDir::NoDotAndDotDot;
QDirIterator it(cacheDirectory(), filters, QDirIterator::Subdirectories);
QMultiMap<QDateTime, QString> cacheItems;
qint64 totalSize = 0;
while (it.hasNext()) {
QString path = it.next();
QFileInfo info = it.fileInfo();
QString fileName = info.fileName();
if (fileName.endsWith(CACHE_POSTFIX)) {
cacheItems.insert(info.created(), path);
totalSize += info.size();
}
}
int removedFiles = 0;
qint64 goal = (maximumCacheSize() * 9) / 10;
QMultiMap<QDateTime, QString>::const_iterator i = cacheItems.constBegin();
while (i != cacheItems.constEnd()) {
if (totalSize < goal)
break;
QString name = i.value();
QFile file(name);
qint64 size = file.size();
file.remove();
totalSize -= size;
++removedFiles;
++i;
}
#if defined(QNETWORKDISKCACHE_DEBUG)
if (removedFiles > 0) {
qDebug() << "QNetworkDiskCache::expire()"
<< "Removed:" << removedFiles
<< "Kept:" << cacheItems.count() - removedFiles;
}
#endif
return totalSize;
}
示例8: run
void CalculateTaskScore::run()
{
qDebug() << "CalculateTaskScore: Starting new thread";
ConfigParser settings;
QDateTime started = QDateTime::currentDateTime();
ctemplate::TemplateDictionary dict("user_task_score");
db = MySQLHandler::getInstance();
QMultiMap<int, LCCode> users = UserDao::getUserNativeLCCodes(db);
QList<QSharedPointer<Task> > tasks = this->getTasks(); //Must use custom function to check message for task id
QMultiMap<int, LCCode> userSecondaryLanguages = UserDao::getUserLCCodes(db);
QMultiMap<int, int> userTags = UserDao::getUserTagIds(db);
QMultiMap<int, int> taskTags = TaskDao::getTaskTagIds(db);
if(users.count() > 0) {
for(QMultiMap<int, LCCode>::ConstIterator usersIter = users.constBegin(); usersIter != users.constEnd(); ++usersIter) {
if(tasks.length() > 0) {
const LCCode userNativeLCCode = users.value(usersIter.key());
QList<TaskScore> taskScores;
foreach(QSharedPointer<Task> task, tasks) {
int score = 0;
Locale taskSourceLocale = task->sourcelocale();
if(userNativeLCCode.first == taskSourceLocale.languagecode()) {
score += 750;
if(userNativeLCCode.second == taskSourceLocale.countrycode()) {
score += 75;
}
}
Locale taskTargetLocale = task->targetlocale();
if(userNativeLCCode.first == taskTargetLocale.languagecode()) {
score += 1000;
if(userNativeLCCode.second == taskTargetLocale.countrycode()) {
score += 100;
}
}
if(userSecondaryLanguages.contains(usersIter.key())) {
const QList<LCCode> lcCodes = userSecondaryLanguages.values(usersIter.key());
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskSourceLocale.languagecode()))) {
score += 500;
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskSourceLocale.countrycode())) ) {
score += 50;
}
}
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskTargetLocale.languagecode()))) {
score += 500;
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskTargetLocale.countrycode())) ) {
score += 50;
}
}
}
if(userTags.contains(usersIter.key()) && taskTags.contains(task->id())) {
int increment_value = 250;
QList<int> userTagIds = userTags.values(usersIter.key());
QList<int> userTaskTagIds = taskTags.values(task->id());
foreach(int userTagId, userTagIds) {
if(userTaskTagIds.contains(userTagId)) {
score += increment_value;
increment_value *= 0.75;
}
}
}
QDateTime created_time = QDateTime::fromString(
QString::fromStdString(task->createdtime()), Qt::ISODate);
//increase score by one per day since created time
score += created_time.daysTo(QDateTime::currentDateTime());
taskScores.append(TaskScore(task->id(), score));
}
this->saveUserTaskScore(usersIter.key(),taskScores);
} else {
示例9: signRequest
QByteArray Token::signRequest(const QUrl& requestUrl, Token::AuthMethod authMethod, Token::HttpMethod method, const QMultiMap<QString, QString>& parameters) const
{
QString timestamp;
QString nonce;
if (d->consumerKey == "test_token") { // Set known values for unit-testing
timestamp = "1234567890"; //Feb 13, 2009, 23:31:30 GMT
nonce = "ABCDEF";
} else {
#if QT_VERSION >= 0x040700
timestamp = QString::number(QDateTime::currentDateTimeUtc().toTime_t());
#else
timestamp = QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
#endif
nonce = QString::number(qrand());
}
if (!requestUrl.isValid()) {
qWarning() << "OAuth::Token: Invalid url. The request will probably be invalid";
}
// Step 1. Get all the oauth params for this request
QMultiMap<QString, QString> oauthParams;
oauthParams.insert("oauth_consumer_key", d->consumerKey);
if(d->serviceType == "dbox")
oauthParams.insert("oauth_signature_method", "PLAINTEXT");
else
oauthParams.insert("oauth_signature_method", "HMAC-SHA1");
oauthParams.insert("oauth_timestamp", timestamp);
oauthParams.insert("oauth_nonce", nonce);
oauthParams.insert("oauth_version", "1.0");
switch (d->tokenType) {
case Token::InvalidToken:
oauthParams.insert("oauth_callback", d->callbackUrl.toString());
break;
case Token::RequestToken:
oauthParams.insert("oauth_token", d->oauthToken);
oauthParams.insert("oauth_verifier", d->oauthVerifier);
break;
case Token::AccessToken:
oauthParams.insert("oauth_token", d->oauthToken);
break;
}
// Step 2. Take the parameters from the url, and add the oauth params to them
QMultiMap<QString, QString> allParams = oauthParams;
QList<QPair<QString, QString> > queryItems = requestUrl.queryItems();
for(int i = 0; i < queryItems.count(); ++i) {
allParams.insert(queryItems[i].first, queryItems[i].second);
}
allParams.unite(parameters);
// Step 3. Calculate the signature from those params, and append the signature to the oauth params
QString signature = generateSignature(requestUrl, allParams, method);
oauthParams.insert("oauth_signature", signature);
// Step 4. Concatenate all oauth params into one comma-separated string
QByteArray authHeader;
if (authMethod == Sasl) {
authHeader = "GET ";
authHeader.append(requestUrl.toString() + " ");
} else {
authHeader = "OAuth ";
}
QMultiMap<QString, QString>::const_iterator p = oauthParams.constBegin();
while (p != oauthParams.constEnd()) {
authHeader += QString("%1=\"%2\",").arg(p.key()).arg(encode(p.value()));
++p;
}
authHeader.chop(1); // remove the last character (the trailing ",")
return authHeader;
}
示例10: main
//.........这里部分代码省略.........
QgsEditorWidgetRegistry::initEditors();
while ( fcgi_accept() >= 0 )
{
QgsMapLayerRegistry::instance()->removeAllMapLayers();
qgsapp.processEvents();
if ( logLevel < 1 )
{
time.start();
printRequestInfos();
}
//Request handler
QScopedPointer<QgsRequestHandler> theRequestHandler( createRequestHandler() );
try
{
// TODO: split parse input into plain parse and processing from specific services
theRequestHandler->parseInput();
}
catch ( QgsMapServiceException& e )
{
QgsMessageLog::logMessage( "Parse input exception: " + e.message(), "Server", QgsMessageLog::CRITICAL );
theRequestHandler->setServiceException( e );
}
#ifdef HAVE_SERVER_PYTHON_PLUGINS
// Set the request handler into the interface for plugins to manipulate it
serverIface.setRequestHandler( theRequestHandler.data() );
// Iterate filters and call their requestReady() method
QgsServerFiltersMap::const_iterator filtersIterator;
for ( filtersIterator = pluginFilters.constBegin(); filtersIterator != pluginFilters.constEnd(); ++filtersIterator )
{
filtersIterator.value()->requestReady();
}
//Pass the filters to the requestHandler, this is needed for the following reasons:
// 1. allow core services to access plugin filters and implement thir own plugin hooks
// 2. allow requestHandler to call sendResponse plugin hook
//TODO: implement this in the requestHandler ctor (far easier if we will get rid of
// HAVE_SERVER_PYTHON_PLUGINS
theRequestHandler->setPluginFilters( pluginFilters );
#endif
// Copy the parameters map
QMap<QString, QString> parameterMap( theRequestHandler->parameterMap() );
printRequestParameters( parameterMap, logLevel );
QMap<QString, QString>::const_iterator paramIt;
//Config file path
QString configFilePath = configPath( defaultConfigFilePath, parameterMap );
//Service parameter
QString serviceString = theRequestHandler->parameter( "SERVICE" );
if ( serviceString.isEmpty() )
{
// SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo
QString requestString = theRequestHandler->parameter( "REQUEST" );
if ( requestString == "GetMap" || requestString == "GetFeatureInfo" )
{
serviceString = "WMS";
}
}
示例11: sendMessage
bool EditWidget::sendMessage()
{
bool sent = false;
if (FSendEnabled)
{
bool hooked = false;
QMultiMap<int, IMessageEditSendHandler *> handlers = FMessageWidgets->editSendHandlers();
for (QMap<int,IMessageEditSendHandler *>::const_iterator it = handlers.constBegin(); !hooked && it!=handlers.constEnd(); ++it)
hooked = (*it)->messageEditSendPrepare(it.key(),this);
for (QMap<int,IMessageEditSendHandler *>::const_iterator it = handlers.constBegin(); !hooked && !sent && it!=handlers.constEnd(); ++it)
sent = (*it)->messageEditSendProcesse(it.key(),this);
if (sent)
{
appendMessageToBuffer();
textEdit()->clear();
emit messageSent();
}
}
return sent;
}
示例12: text
void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
editInfo->clear();
if ( ! current )
return;
const int folder_id = current->data( 0, Qt::UserRole ).toInt();
QString text("Folder: ");
QSqlQuery q;
// self
q.prepare("SELECT "
"name, "
"path, "
"size "
"FROM "
"folders "
"WHERE "
"id = :id ");
q.bindValue(":id", folder_id );
if ( q.exec() ) {
if ( q.first() )
text += q.value( 0 ).toString() + "<BR>" +
"Path: " + q.value( 1 ).toString() + "<BR>" +
"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";
} else {
emit yell( q.lastError().text() );
return;
}
// count of folders
int folderCount = 0;
countFolders( folder_id, folderCount );
// count of types
int typeCount = 0;
QHash< QString, int > types;
countTypes( folder_id, types, typeCount );
// ordering
QMultiMap< int, QString > typesMap;
QHash< QString, int >::const_iterator h = types.constBegin();
while ( h != types.constEnd() ) {
typesMap.insert( h.value(), h.key() );
++h;
}
// percent of folders
text += tr("folders: %1 (%2%)<BR>")
.arg( folderCount )
.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );
// percents of files
chart->clear();
if ( typesMap.count() > 0 ) {
QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();
do {
--mm;
const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;
text += tr("%1: %2 (%3%)<BR>")
.arg( mm.value() )
.arg( mm.key() )
.arg( percent, 0, 'f', 1 );
chart->addPiece( percent, mm.value() );
} while ( mm != typesMap.constBegin() );
}
text += QString( 50, '-' ) + "<BR>"; // horizontal line -------
// folders
text += "<BR><B>folders:</B><BR>";
q.prepare("SELECT "
"name, "
"size "
"FROM "
"folders "
"WHERE "
"parent_id = :id "
"ORDER BY "
"size DESC");
q.bindValue(":id", folder_id );
if ( q.exec() ) {
//.........这里部分代码省略.........
示例13: QWidget
NotifyKindOptionsWidget::NotifyKindOptionsWidget(INotifications *ANotifications, QWidget *AParent) : QWidget(AParent)
{
FNotifications = ANotifications;
tbwNotifies = new QTableWidget(this);
tbwNotifies->setWordWrap(true);
tbwNotifies->verticalHeader()->setVisible(false);
tbwNotifies->horizontalHeader()->setHighlightSections(false);
tbwNotifies->setSelectionMode(QTableWidget::NoSelection);
connect(tbwNotifies,SIGNAL(itemChanged(QTableWidgetItem *)),SIGNAL(modified()));
tbwNotifies->setColumnCount(NTC__COUNT);
tbwNotifies->setHorizontalHeaderLabels(QStringList() << tr("Event") << "" << "" << "" << "" );
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TYPE,QHeaderView::Stretch);
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_SOUND,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setToolTip(tr("Play sound at the notification"));
tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SOUNDPLAY));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_POPUP,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setToolTip(tr("Display a notification in popup window"));
tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_PUPUPWINDOW));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_MINIMIZED,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setToolTip(tr("Show the corresponding window minimized in the taskbar"));
tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SHOWMINIMIZED));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TRAY,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setToolTip(tr("Display a notification icon in the system tray"));
tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_TRAYICON));
QVBoxLayout *vblLayout = new QVBoxLayout(this);
vblLayout->addWidget(tbwNotifies);
vblLayout->setMargin(0);
QMultiMap<int, NotificationType> orderedTypes;
ushort visibleKinds = INotification::PopupWindow|INotification::TrayNotify|INotification::SoundPlay|INotification::ShowMinimized;
foreach(const QString &typeId, FNotifications->notificationTypes())
{
NotificationType notifyType = FNotifications->notificationType(typeId);
if (!notifyType.title.isEmpty() && (notifyType.kindMask & visibleKinds)>0)
{
notifyType.typeId = typeId;
orderedTypes.insertMulti(notifyType.order,notifyType);
}
}
for (QMultiMap<int, NotificationType>::const_iterator it=orderedTypes.constBegin(); it!=orderedTypes.constEnd(); ++it)
{
int row = tbwNotifies->rowCount();
tbwNotifies->setRowCount(row+1);
QTableWidgetItem *type = new QTableWidgetItem(it->icon,it->title);
type->setData(NTR_TYPE, it->typeId);
type->setFlags(Qt::ItemIsEnabled);
tbwNotifies->setItem(row,NTC_TYPE,type);
QTableWidgetItem *sound = new QTableWidgetItem();
sound->setData(NTR_KIND, INotification::SoundPlay);
if (it->kindMask & INotification::SoundPlay)
sound->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
sound->setFlags(Qt::ItemIsUserCheckable);
sound->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_SOUND,sound);
QTableWidgetItem *popup = new QTableWidgetItem();
popup->setData(NTR_KIND, INotification::PopupWindow);
if (it->kindMask & INotification::PopupWindow)
popup->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
popup->setFlags(Qt::ItemIsUserCheckable);
popup->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_POPUP,popup);
QTableWidgetItem *minimized = new QTableWidgetItem();
minimized->setData(NTR_KIND, INotification::ShowMinimized);
if (it->kindMask & INotification::ShowMinimized)
minimized->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
minimized->setFlags(Qt::ItemIsUserCheckable);
minimized->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_MINIMIZED,minimized);
tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
QTableWidgetItem *tray = new QTableWidgetItem();
tray->setData(NTR_KIND, INotification::TrayNotify);
if (it->kindMask & INotification::TrayNotify)
tray->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
tray->setFlags(Qt::ItemIsUserCheckable);
tray->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_TRAY,tray);
tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
}
reset();
}
示例14: shuffleTracks
void Playlist::shuffleTracks(MusicPlayer::ShuffleMode shuffleMode)
{
m_shuffledSongs.clear();
switch (shuffleMode)
{
case MusicPlayer::SHUFFLE_RANDOM:
{
QMultiMap<int, MusicMetadata*> songMap;
SongList::const_iterator it = m_songs.begin();
for (; it != m_songs.end(); ++it)
{
songMap.insert(rand(), *it);
}
QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
while (i != songMap.constEnd())
{
m_shuffledSongs.append(i.value());
++i;
}
break;
}
case MusicPlayer::SHUFFLE_INTELLIGENT:
{
int RatingWeight = 2;
int PlayCountWeight = 2;
int LastPlayWeight = 2;
int RandomWeight = 2;
m_parent->FillIntelliWeights(RatingWeight, PlayCountWeight,
LastPlayWeight, RandomWeight);
// compute max/min playcount,lastplay for this playlist
int playcountMin = 0;
int playcountMax = 0;
double lastplayMin = 0.0;
double lastplayMax = 0.0;
uint idx = 0;
SongList::const_iterator it = m_songs.begin();
for (; it != m_songs.end(); ++it, ++idx)
{
if (!(*it)->isCDTrack())
{
MusicMetadata *mdata = (*it);
if (0 == idx)
{
// first song
playcountMin = playcountMax = mdata->PlayCount();
lastplayMin = lastplayMax = mdata->LastPlay().toTime_t();
}
else
{
if (mdata->PlayCount() < playcountMin)
playcountMin = mdata->PlayCount();
else if (mdata->PlayCount() > playcountMax)
playcountMax = mdata->PlayCount();
if (mdata->LastPlay().toTime_t() < lastplayMin)
lastplayMin = mdata->LastPlay().toTime_t();
else if (mdata->LastPlay().toTime_t() > lastplayMax)
lastplayMax = mdata->LastPlay().toTime_t();
}
}
}
// next we compute all the weights
std::map<int,double> weights;
std::map<int,int> ratings;
std::map<int,int> ratingCounts;
int TotalWeight = RatingWeight + PlayCountWeight + LastPlayWeight;
for (int trackItI = 0; trackItI < m_songs.size(); ++trackItI)
{
MusicMetadata *mdata = m_songs[trackItI];
if (!mdata->isCDTrack())
{
int rating = mdata->Rating();
int playcount = mdata->PlayCount();
double lastplaydbl = mdata->LastPlay().toTime_t();
double ratingValue = (double)(rating) / 10;
double playcountValue, lastplayValue;
if (playcountMax == playcountMin)
playcountValue = 0;
else
playcountValue = ((playcountMin - (double)playcount) / (playcountMax - playcountMin) + 1);
if (lastplayMax == lastplayMin)
lastplayValue = 0;
else
lastplayValue = ((lastplayMin - lastplaydbl) / (lastplayMax - lastplayMin) + 1);
double weight = (RatingWeight * ratingValue +
PlayCountWeight * playcountValue +
LastPlayWeight * lastplayValue) / TotalWeight;
weights[mdata->ID()] = weight;
//.........这里部分代码省略.........
示例15: convexHull
bool QgsGeometryAnalyzer::convexHull( QgsVectorLayer* layer, const QString& shapefileName,
bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
if ( !layer )
{
return false;
}
QgsVectorDataProvider* dp = layer->dataProvider();
if ( !dp )
{
return false;
}
bool useField = false;
if ( uniqueIdField == -1 )
{
uniqueIdField = 0;
}
else
{
useField = true;
}
QgsFields fields;
fields.append( QgsField( QStringLiteral( "UID" ), QVariant::String ) );
fields.append( QgsField( QStringLiteral( "AREA" ), QVariant::Double ) );
fields.append( QgsField( QStringLiteral( "PERIM" ), QVariant::Double ) );
QgsWkbTypes::Type outputType = QgsWkbTypes::Polygon;
QgsCoordinateReferenceSystem crs = layer->crs();
QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, crs );
QgsFeature currentFeature;
QgsGeometry dissolveGeometry; //dissolve geometry
QMultiMap<QString, QgsFeatureId> map;
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
QgsFeatureIds::const_iterator it = selection.constBegin();
for ( ; it != selection.constEnd(); ++it )
{
#if 0
if ( p )
{
p->setValue( processedFeatures );
}
if ( p && p->wasCanceled() )
{
// break; // it may be better to do something else here?
return false;
}
#endif
if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) )
{
continue;
}
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
else
{
QgsFeatureIterator fit = layer->getFeatures();
while ( fit.nextFeature( currentFeature ) )
{
#if 0
if ( p )
{
p->setValue( processedFeatures );
}
if ( p && p->wasCanceled() )
{
// break; // it may be better to do something else here?
return false;
}
#endif
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
while ( jt != map.constEnd() )
{
QString currentKey = jt.key();
int processedFeatures = 0;
//take only selection
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
if ( p )
{
p->setMaximum( selection.size() );
}
processedFeatures = 0;
while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
{
if ( p && p->wasCanceled() )
{
break;
}
//.........这里部分代码省略.........