本文整理汇总了C++中QList::size方法的典型用法代码示例。如果您正苦于以下问题:C++ QList::size方法的具体用法?C++ QList::size怎么用?C++ QList::size使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QList
的用法示例。
在下文中一共展示了QList::size方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: open
bool QAudioInputPrivate::open()
{
#ifdef DEBUG_AUDIO
QTime now(QTime::currentTime());
qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
clockStamp.restart();
timeStamp.restart();
elapsedTimeOffset = 0;
int dir;
int err = 0;
int count=0;
unsigned int freakuency=settings.frequency();
if (!settings.isValid()) {
qWarning("QAudioOutput: open error, invalid format.");
} else if (settings.sampleRate() <= 0) {
qWarning("QAudioOutput: open error, invalid sample rate (%d).",
settings.sampleRate());
} else {
err = -1;
}
if (err == 0) {
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit errorChanged(errorState);
return false;
}
QString dev = QString(QLatin1String(m_device.constData()));
QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioInput);
if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
if (devices.size() > 0)
dev = QLatin1String(devices.first());
else
return false;
#else
dev = QLatin1String("hw:0,0");
#endif
} else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
dev = QLatin1String(m_device);
#else
int idx = 0;
char *name;
QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData());
while(snd_card_get_name(idx,&name) == 0) {
if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0)
break;
idx++;
}
dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
}
// Step 1: try and open the device
while((count < 5) && (err < 0)) {
err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0);
if(err < 0)
count++;
}
if (( err < 0)||(handle == 0)) {
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
return false;
}
snd_pcm_nonblock( handle, 0 );
// Step 2: Set the desired HW parameters.
snd_pcm_hw_params_alloca( &hwparams );
bool fatal = false;
QString errMessage;
unsigned int chunks = 8;
err = snd_pcm_hw_params_any( handle, hwparams );
if ( err < 0 ) {
fatal = true;
errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_any: err = %1").arg(err);
}
if ( !fatal ) {
err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 );
if ( err < 0 ) {
fatal = true;
errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err);
}
}
if ( !fatal ) {
err = snd_pcm_hw_params_set_access( handle, hwparams, access );
if ( err < 0 ) {
fatal = true;
errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_access: err = %1").arg(err);
}
//.........这里部分代码省略.........
示例2: col
//.........这里部分代码省略.........
mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) );
mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) );
mDiagramSizeSpinBox->setValue( 30 );
mBarWidthSpinBox->setValue( 5 );
mVisibilityGroupBox->setChecked( false );
switch ( layerType )
{
case QGis::Point:
mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
break;
case QGis::Line:
mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 3 ) );
mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( 2 ) );
break;
case QGis::Polygon:
mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
break;
case QGis::UnknownGeometry:
case QGis::NoGeometry:
break;
}
mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) );
}
else // already a diagram renderer present
{
mDisplayDiagramsGroupBox->setChecked( true );
//single category renderer or interpolated one?
mFixedSizeCheckBox->setChecked( dr->rendererName() == "SingleCategory" );
//assume single category or linearly interpolated diagram renderer for now
QList<QgsDiagramSettings> settingList = dr->diagramSettings();
if ( settingList.size() > 0 )
{
mDiagramFont = settingList.at( 0 ).font;
QSizeF size = settingList.at( 0 ).size;
mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor );
mTransparencySlider->setValue( settingList.at( 0 ).transparency );
mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor );
mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth );
mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 );
mMinimumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).minScaleDenominator, 'f' ) );
mMaximumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).maxScaleDenominator, 'f' ) );
mVisibilityGroupBox->setChecked( settingList.at( 0 ).minScaleDenominator != -1 &&
settingList.at( 0 ).maxScaleDenominator != -1 );
if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM )
{
mDiagramUnitComboBox->setCurrentIndex( 0 );
}
else
{
mDiagramUnitComboBox->setCurrentIndex( 1 );
}
if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height )
{
mLabelPlacementComboBox->setCurrentIndex( 0 );
}
else
{
mLabelPlacementComboBox->setCurrentIndex( 1 );
}
mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left );
mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right );
示例3: rec
void ParserTests::testMemcheckSample1()
{
initTest(QLatin1String("memcheck-output-sample1.xml"));
QList<Error> expectedErrors;
{
Error error;
error.setKind(InvalidRead);
error.setWhat(QLatin1String("Invalid read of size 4"));
error.setUnique(0x9);
error.setTid(1);
Frame f1;
f1.setInstructionPointer(0x6E47964);
f1.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0"));
f1.setFunctionName(QLatin1String("QFrame::frameStyle() const"));
f1.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/widgets"));
f1.setFile(QLatin1String("qframe.cpp"));
f1.setLine(252);
Frame f2;
f2.setInstructionPointer(0x118F2AF7);
f2.setObject(QLatin1String("/usr/lib/kde4/plugins/styles/oxygen.so"));
Frame f3;
f3.setInstructionPointer(0x6A81671);
f3.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0"));
f3.setFunctionName(QLatin1String("QWidget::event(QEvent*)"));
f3.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel"));
f3.setFile(QLatin1String("qwidget.cpp"));
f3.setLine(8273);
Frame f4;
f4.setInstructionPointer(0x6A2B6EB);
f4.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0"));
f4.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel"));
f4.setFile(QLatin1String("qapplication.cpp"));
f4.setFunctionName(QLatin1String("QApplicationPrivate::notify_helper(QObject*, QEvent*)"));
f4.setLine(4396);
Stack s1;
s1.setAuxWhat(QLatin1String("Address 0x11527cb8 is not stack'd, malloc'd or (recently) free'd"));
s1.setFrames(QVector<Frame>() << f1 << f2 << f3 << f4);
error.setStacks( QVector<Stack>() << s1 );
expectedErrors << error;
}
QVector<QPair<qint64,qint64> > expectedErrorCounts;
expectedErrorCounts.push_back(QPair<qint64,qint64>(9, 2));
QVector<QPair<QString,qint64> > expectedSuppCounts;
expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("X on SUSE11 writev uninit padding"), static_cast<qint64>(12)));
expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("dl-hack3-cond-1"), static_cast<qint64>(2)));
expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("glibc-2.5.x-on-SUSE-10.2-(PPC)-2a"), static_cast<qint64>(2)));
Valgrind::XmlProtocol::Parser parser;
Recorder rec(&parser);
parser.parse(m_socket);
m_process->waitForFinished();
QCOMPARE(m_process->exitStatus(), QProcess::NormalExit);
QCOMPARE(m_process->state(), QProcess::NotRunning);
QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString()));
const QList<Error> actualErrors = rec.errors;
if (actualErrors.first() != expectedErrors.first()) {
dumpError(actualErrors.first());
dumpError(expectedErrors.first());
}
QCOMPARE(actualErrors.first(), expectedErrors.first());
QCOMPARE(actualErrors.size(), 3);
QCOMPARE(rec.errorcounts, expectedErrorCounts);
QCOMPARE(rec.suppcounts, expectedSuppCounts);
}
示例4: insertFromMimeData
void VMdEditor::insertFromMimeData(const QMimeData *p_source)
{
VSelectDialog dialog(tr("Insert From Clipboard"), this);
dialog.addSelection(tr("Insert As Image"), 0);
dialog.addSelection(tr("Insert As Text"), 1);
if (p_source->hasHtml()) {
// Handle <img>.
QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>");
if (reg.indexIn(p_source->html()) != -1) {
m_editOps->insertImageFromURL(QUrl(reg.cap(2)));
return;
}
}
if (p_source->hasImage()) {
// Image data in the clipboard
if (p_source->hasText()) {
if (dialog.exec() == QDialog::Accepted) {
if (dialog.getSelection() == 1) {
// Insert as text.
Q_ASSERT(p_source->hasText() && p_source->hasImage());
VTextEdit::insertFromMimeData(p_source);
return;
}
} else {
return;
}
}
m_editOps->insertImageFromMimeData(p_source);
return;
}
if (p_source->hasUrls()) {
QList<QUrl> urls = p_source->urls();
if (urls.size() == 1 && VUtils::isImageURL(urls[0])) {
if (dialog.exec() == QDialog::Accepted) {
// FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
if (dialog.getSelection() == 0) {
// Insert as image.
m_editOps->insertImageFromURL(urls[0]);
return;
}
QMimeData newSource;
newSource.setUrls(urls);
VTextEdit::insertFromMimeData(&newSource);
return;
} else {
return;
}
}
}
if (p_source->hasText()) {
QString text = p_source->text();
if (VUtils::isImageURLText(text)) {
// The text is a URL to an image.
if (dialog.exec() == QDialog::Accepted) {
if (dialog.getSelection() == 0) {
// Insert as image.
QUrl url(text);
if (url.isValid()) {
m_editOps->insertImageFromURL(QUrl(text));
}
return;
}
} else {
return;
}
}
Q_ASSERT(p_source->hasText());
}
VTextEdit::insertFromMimeData(p_source);
}
示例5: updateWallet
/* Update our model of the wallet incrementally, to synchronize our model of the wallet
with that of the core.
Call with transaction that was added, removed or changed.
*/
void updateWallet(const uint256 &hash, int status)
{
OutputDebugStringF("updateWallet %s %i\n", hash.ToString().c_str(), status);
{
LOCK(wallet->cs_wallet);
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
bool inWallet = mi != wallet->mapWallet.end();
// Find bounds of this transaction in model
QList<TransactionRecord>::iterator lower = qLowerBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
QList<TransactionRecord>::iterator upper = qUpperBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
int lowerIndex = (lower - cachedWallet.begin());
int upperIndex = (upper - cachedWallet.begin());
bool inModel = (lower != upper);
// Determine whether to show transaction or not
bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));
if(status == CT_UPDATED)
{
if(showTransaction && !inModel)
status = CT_NEW; /* Not in model, but want to show, treat as new */
if(!showTransaction && inModel)
status = CT_DELETED; /* In model, but want to hide, treat as deleted */
}
OutputDebugStringF(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n",
inWallet, inModel, lowerIndex, upperIndex, showTransaction, status);
switch(status)
{
case CT_NEW:
if(inModel)
{
OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n");
break;
}
if(!inWallet)
{
OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n");
break;
}
if(showTransaction)
{
// Added -- insert at the right position
QList<TransactionRecord> toInsert =
TransactionRecord::decomposeTransaction(wallet, mi->second);
if(!toInsert.isEmpty()) /* only if something to insert */
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
int insert_idx = lowerIndex;
foreach(const TransactionRecord &rec, toInsert)
{
cachedWallet.insert(insert_idx, rec);
insert_idx += 1;
}
parent->endInsertRows();
}
}
break;
case CT_DELETED:
if(!inModel)
{
OutputDebugStringF("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n");
break;
}
// Removed -- remove entire transaction from table
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedWallet.erase(lower, upper);
parent->endRemoveRows();
break;
case CT_UPDATED:
// Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
// visible transactions.
break;
}
示例6: computeFillRegion
QRegion TilePainter::computeFillRegion(const QPoint &fillOrigin) const {
//create that region that will hold the fill
QRegion fillRegion;
//silently quit if parameters are unsatisfactory
if (!isDrawable(fillOrigin.x(), fillOrigin.y()))
return fillRegion;
//cache cell that we will match other cells against
const Cell matchCell = cellAt(fillOrigin.x(), fillOrigin.y());
//grab map dimensions for later use.
const int mapWidth = mMapEditor->map()->width();
const int mapHeight = mMapEditor->map()->height();
const int mapSize = mapWidth * mapHeight;
//create a queue to hold cells that need filling
QList<QPoint> fillPositions;
fillPositions.append(fillOrigin);
qDebug() << "fix " << fillPositions.at(0).x();
qDebug() << "fiy " << fillPositions.at(0).y();
//create an array that will store which cells have been processed
//this is faster than checking if a given cell is in the region/list
QVector<quint8> processedCellsVec(mapSize);
quint8 *processedCells = processedCellsVec.data();
//loop through queued positions and fill them, while at the same time
//checking adjacent positions to see if they should be added
while (!fillPositions.isEmpty()) {
for (int i = 0; i < fillPositions.size(); ++i) {
qDebug() << "fx " << fillPositions.at(i).x();
qDebug() << "fy " << fillPositions.at(i).y();
}
const QPoint currentPoint = fillPositions.takeFirst();
//qDebug() << "cpx" << currentPoint.x();
//qDebug() << "cpy" << currentPoint.y();
const int startOfLine = currentPoint.y() * mapWidth;
//seek as far left as we can
int left = currentPoint.x();
while (cellAt(left - 1, currentPoint.y()) == matchCell &&
isDrawable(left - 1, currentPoint.y()))
--left;
//seek as far right as we can
int right = currentPoint.x();
while (cellAt(right + 1, currentPoint.y()) == matchCell &&
isDrawable(right + 1, currentPoint.y()))
++right;
qDebug() << left;
//add cells between left and right to the region
fillRegion += QRegion(left, currentPoint.y(), right - left + 1, 1);
//add cell strip to processed cells
memset(&processedCells[startOfLine + left],
1,
right - left);
//these variables cache whether the last cell was added to the queue
//or not as an optimization, since adjacent cells on the x axis
//do not need to be added to the queue.
bool lastAboveCell = false;
bool lastBelowCell = false;
//loop between left and right and check if cells above or
//below need to be added to the queue
for (int x = left; x <= right; ++x) {
const QPoint fillPoint(x, currentPoint.y());
//check cell above
if (fillPoint.y() > 0) {
QPoint aboveCell(fillPoint.x(), fillPoint.y() - 1);
if (!processedCells[aboveCell.y() * mapWidth + aboveCell.x()] &&
cellAt(aboveCell.x(), aboveCell.y()) == matchCell &&
isDrawable(aboveCell.x(), aboveCell.y()))
{
//do not add the above cell to the queue if its
//x-adjacent cell was added.
if (!lastAboveCell)
fillPositions.append(aboveCell);
lastAboveCell = true;
} else lastAboveCell = false;
processedCells[aboveCell.y() * mapWidth + aboveCell.x()] = 1;
}
//check cell below
if (fillPoint.y() + 1 < mapHeight) {
QPoint belowCell(fillPoint.x(), fillPoint.y() + 1);
if (!processedCells[belowCell.y()*mapWidth + belowCell.x()] &&
cellAt(belowCell.x(), belowCell.y()) == matchCell &&
//.........这里部分代码省略.........
示例7: loadPlayerScript
bool loadPlayerScript(QString path, int player, int difficulty)
{
ASSERT_OR_RETURN(false, player < MAX_PLAYERS, "Player index %d out of bounds", player);
QScriptEngine *engine = new QScriptEngine();
UDWORD size;
char *bytes = NULL;
if (!loadFile(path.toAscii().constData(), &bytes, &size))
{
debug(LOG_ERROR, "Failed to read script file \"%s\"", path.toAscii().constData());
return false;
}
QString source = QString::fromAscii(bytes, size);
free(bytes);
QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source);
ASSERT_OR_RETURN(false, syntax.state() == QScriptSyntaxCheckResult::Valid, "Syntax error in %s line %d: %s",
path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData());
// Special functions
engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer));
engine->globalObject().setProperty("queue", engine->newFunction(js_queue));
engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer));
engine->globalObject().setProperty("include", engine->newFunction(js_include));
engine->globalObject().setProperty("bind", engine->newFunction(js_bind));
// Special global variables
//== \item[version] Current version of the game, set in \emph{major.minor} format.
engine->globalObject().setProperty("version", "3.2", QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[selectedPlayer] The player ontrolled by the client on which the script runs.
engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[gameTime] The current game time. Updated before every invokation of a script.
engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[difficulty] The currently set campaign difficulty, or the current AI's difficulty setting. It will be one of
//== EASY, MEDIUM, HARD or INSANE.
if (game.type == SKIRMISH)
{
engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable);
}
else // campaign
{
engine->globalObject().setProperty("difficulty", (int)getDifficultyLevel(), QScriptValue::ReadOnly | QScriptValue::Undeletable);
}
//== \item[mapName] The name of the current map.
engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[baseType] The type of base that the game starts with. It will be one of CAMP_CLEAN, CAMP_BASE or CAMP_WALLS.
engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[alliancesType] The type of alliances permitted in this game. It will be one of NO_ALLIANCES, ALLIANCES or ALLIANCES_TEAMS.
engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[powerType] The power level set for this game.
engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[maxPlayers] The number of active players in this game.
engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[scavengers] Whether or not scavengers are activated in this game.
engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[mapWidth] Width of map in tiles.
engine->globalObject().setProperty("mapWidth", mapWidth, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[mapHeight] Height of map in tiles.
engine->globalObject().setProperty("mapHeight", mapHeight, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[scavengerPlayer] Index of scavenger player. (3.2+ only)
engine->globalObject().setProperty("scavengerPlayer", scavengerPlayer(), QScriptValue::ReadOnly | QScriptValue::Undeletable);
// Regular functions
QFileInfo basename(path);
registerFunctions(engine, basename.baseName());
// Remember internal, reserved names
QScriptValueIterator it(engine->globalObject());
while (it.hasNext())
{
it.next();
internalNamespace.insert(it.name(), 1);
}
// We need to always save the 'me' special variable.
//== \item[me] The player the script is currently running as.
engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
QScriptValue result = engine->evaluate(source, path);
ASSERT_OR_RETURN(false, !engine->hasUncaughtException(), "Uncaught exception at line %d, file %s: %s",
engine->uncaughtExceptionLineNumber(), path.toAscii().constData(), result.toString().toAscii().constData());
// We also need to save the special 'scriptName' variable.
//== \item[scriptName] Base name of the script that is running.
engine->globalObject().setProperty("scriptName", basename.baseName(), QScriptValue::ReadOnly | QScriptValue::Undeletable);
// Register script
scripts.push_back(engine);
debug(LOG_SAVE, "Created script engine %d for player %d from %s", scripts.size() - 1, player, path.toUtf8().constData());
return true;
}
示例8: hoverMoveEvent
void QDeclarativeGraphicsGeoMap::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
if (!mapData_)
return;
QList<QGeoMapObject*> objectsThen = mapData_->mapObjectsAtScreenPosition(event->lastPos());
QList<QGeoMapObject*> objectsNow = mapData_->mapObjectsAtScreenPosition(event->pos());
QSet<QGeoMapObject*> enter = objectsNow.toSet();
enter -= objectsThen.toSet();
for (int i = 0; i < objectsNow.size(); ++i) {
if (!enter.contains(objectsNow.at(i)))
continue;
QDeclarativeGeoMapObject* mapObject = objectMap_.value(objectsNow.at(i), 0);
if (mapObject)
mapObject->enterEvent();
}
QSet<QGeoMapObject*> exit = objectsThen.toSet();
exit -= objectsNow.toSet();
for (int i = 0; i < objectsThen.size(); ++i) {
if (!exit.contains(objectsThen.at(i)))
continue;
QDeclarativeGeoMapObject* mapObject = objectMap_.value(objectsThen.at(i), 0);
if (mapObject)
mapObject->exitEvent();
}
QSet<QGeoMapObject*> move = objectsNow.toSet();
move += objectsThen.toSet();
QList<QGeoMapObject*> objects = mapData_->mapObjectsInViewport();
QDeclarativeGeoMapMouseEvent *mouseEvent = createMapMouseEvent(event);
for (int i = 0; i < objects.size(); ++i) {
if (!move.contains(objects.at(i)))
continue;
QDeclarativeGeoMapObject* mapObject = objectMap_.value(objects.at(i), 0);
if (mapObject)
mapObject->moveEvent(mouseEvent);
}
/*
QList<QGeoMapObject*> objects = mapData_->mapObjectsAtScreenPosition(event->pos());
for (int i = objects.size() - 1; i >= 0; --i) {
QDeclarativeGeoMapObject* mapObject = objectMap_.value(objects.at(i), 0);
if (mapObject)
mapObject->moveEvent(mouseEvent);
}
*/
for (int i = 0; i < mouseAreas_.size(); ++i)
mouseAreas_.at(i)->moveEvent(mouseEvent);
delete mouseEvent;
}
示例9: layout
void System::layout(qreal xo1)
{
if (isVbox()) // ignore vbox
return;
static const Spatium instrumentNameOffset(1.0);
int nstaves = _staves.size();
if (nstaves != score()->nstaves())
qDebug("System::layout: nstaves %d != %d", nstaves, score()->nstaves());
//---------------------------------------------------
// find x position of staves
// create brackets
//---------------------------------------------------
qreal xoff2 = 0.0; // x offset for instrument name
int bracketLevels = 0;
for (int idx = 0; idx < nstaves; ++idx)
bracketLevels = qMax(bracketLevels, score()->staff(idx)->bracketLevels());
qreal bracketWidth[bracketLevels];
for (int i = 0; i < bracketLevels; ++i)
bracketWidth[i] = 0.0;
QList<Bracket*> bl = _brackets;
_brackets.clear();
for (int staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
Staff* s = score()->staff(staffIdx);
for (int i = 0; i < bracketLevels; ++i) {
if (s->bracket(i) == BracketType::NO_BRACKET)
continue;
int firstStaff = staffIdx;
int lastStaff = staffIdx + s->bracketSpan(i) - 1;
if (lastStaff >= nstaves)
lastStaff = nstaves - 1;
for (; firstStaff <= lastStaff; ++firstStaff) {
if (score()->staff(firstStaff)->show())
break;
}
for (; lastStaff >= firstStaff; --lastStaff) {
if (score()->staff(lastStaff)->show())
break;
}
int span = lastStaff - firstStaff + 1;
//
// do not show bracket if it only spans one
// system due to some invisible staves
//
if ((span > 1) || (s->bracketSpan(i) == span)) {
//
// this bracket is visible
//
Bracket* b = 0;
int track = staffIdx * VOICES;
for (int k = 0; k < bl.size(); ++k) {
if (bl[k]->track() == track && bl[k]->level() == i) {
b = bl.takeAt(k);
break;
}
}
if (b == 0) {
b = new Bracket(score());
b->setGenerated(true);
b->setParent(this);
b->setTrack(track);
b->setLevel(i);
b->setBracketType(s->bracket(i));
b->setSpan(s->bracketSpan(i));
score()->undoAddElement(b);
}
else
_brackets.append(b);
b->setFirstStaff(firstStaff);
b->setLastStaff(lastStaff);
bracketWidth[i] = qMax(bracketWidth[i], b->width());
}
}
if (!s->show())
continue;
for (InstrumentName* t : _staves[staffIdx]->instrumentNames) {
t->layout();
qreal w = t->width() + point(instrumentNameOffset);
if (w > xoff2)
xoff2 = w;
}
}
for (Bracket* b : bl)
score()->undoRemoveElement(b);
//---------------------------------------------------
// layout SysStaff and StaffLines
//---------------------------------------------------
// xoff2 += xo1;
_leftMargin = xoff2;
//.........这里部分代码省略.........
示例10: makeTable
void makeTable(const Keyword keywords[])
{
int i,c;
bool pre = (keywords == pp_keywords);
QList<State> states;
states += State(pre?"PP_NOTOKEN":"NOTOKEN");
// identifiers
for (c = 'a'; c <= 'z'; ++c)
newState(states, pre?"PP_CHARACTER":"CHARACTER", c);
for (c = 'A'; c <= 'Z'; ++c)
newState(states, pre?"PP_CHARACTER":"CHARACTER", c);
c = '_';
newState(states, pre?"PP_CHARACTER":"CHARACTER", c);
// add digits
for (c = '0'; c <= '9'; ++c)
newState(states, pre?"PP_DIGIT":"DIGIT", c);
// keywords
for (i = 0; keywords[i].lexem; ++i)
newState(states, keywords[i].token, keywords[i].lexem, pre);
// some floats
for (c = '0'; c <= '9'; ++c)
newState(states, pre?"PP_FLOATING_LITERAL":"FLOATING_LITERAL",
QByteArray(".") + char(c), pre);
// simplify table with default transitions
int transindex = -1;
for (i = 0; i < states.size(); ++i) {
int n = 0;
int defchar = -1;
for (c = 0; c < 128; ++c)
if (states[i].next[c]) {
++n;
defchar = c;
}
if (!n)
continue;
if (n == 1) {
states[i].defnext = states[i].next[defchar];
states[i].defchar = defchar;
continue;
}
states[i].nextindex = ++transindex;
}
#if 1
// compress table
int j, k;
for (i = 0; i < states.size(); ++i) {
for (j = i + 1; j < states.size(); ++j) {
if ( states[i] == states[j] ) {
for (k = 0; k < states.size(); ++k) {
if (states[k].defnext == j)
states[k].defnext = i;
if (states[k].defnext > j)
--states[k].defnext;
for (c = 0; c < 128; ++c) {
if (states[k].next[c] == j)
states[k].next[c] = i;
if (states[k].next[c] > j)
--states[k].next[c];
}
}
states.removeAt(j);
--j;
}
}
}
#endif
printf("static const short %skeyword_trans[][128] = {\n",
pre?"pp_":"");
for (i = 0; i < states.size(); ++i) {
if (i && !states[i].nextindex)
continue;
printf("%s {", i?",\n":"");
for (c = 0; c < 128; ++c)
printf("%s%s%d",
c?",":"",
(!c || c%16)?"":"\n ",
states[i].next[c]
);
printf("}");
}
printf("\n};\n\n");
printf("static const struct\n{\n"
" %sToken token;\n"
" short next;\n"
" char defchar;\n"
" short defnext;\n"
" %sToken ident;\n"
"} %skeywords[] = {\n",
pre ? "PP_":"",
pre ? "PP_":"",
pre ? "pp_":"");
for (i = 0; i < states.size(); ++i) {
printf("%s {%s, %d, %d, %d, %s}",
//.........这里部分代码省略.........
示例11: printPdf
void DrawingView::printPdf()
{
Gui::FileOptionsDialog dlg(this, 0);
dlg.setFileMode(QFileDialog::AnyFile);
dlg.setAcceptMode(QFileDialog::AcceptSave);
dlg.setWindowTitle(tr("Export PDF"));
dlg.setNameFilters(QStringList() << QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file")));
QGridLayout *gridLayout;
QGridLayout *formLayout;
QGroupBox *groupBox;
QListWidget *listWidget;
QListWidgetItem* item;
QWidget *form = new QWidget(&dlg);
form->resize(40, 300);
formLayout = new QGridLayout(form);
groupBox = new QGroupBox(form);
gridLayout = new QGridLayout(groupBox);
listWidget = new QListWidget(groupBox);
gridLayout->addWidget(listWidget, 0, 0, 1, 1);
formLayout->addWidget(groupBox, 0, 0, 1, 1);
groupBox->setTitle(tr("Page sizes"));
item = new QListWidgetItem(tr("A0"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A0));
item = new QListWidgetItem(tr("A1"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A1));
item = new QListWidgetItem(tr("A2"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A2));
item = new QListWidgetItem(tr("A3"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A3));
item = new QListWidgetItem(tr("A4"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A4));
item = new QListWidgetItem(tr("A5"), listWidget);
item->setData(Qt::UserRole, QVariant(QPrinter::A5));
int index = 4; // by default A4
for (int i=0; i<listWidget->count(); i++) {
if (listWidget->item(i)->data(Qt::UserRole).toInt() == m_pageSize) {
index = i;
break;
}
}
listWidget->item(index)->setSelected(true);
dlg.setOptionsWidget(Gui::FileOptionsDialog::ExtensionRight, form, false);
if (dlg.exec() == QDialog::Accepted) {
Gui::WaitCursor wc;
QString filename = dlg.selectedFiles().front();
QPrinter printer(QPrinter::HighResolution);
printer.setFullPage(true);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filename);
printer.setOrientation(m_orientation);
QList<QListWidgetItem*> items = listWidget->selectedItems();
if (items.size() == 1) {
int AX = items.front()->data(Qt::UserRole).toInt();
printer.setPaperSize(QPrinter::PageSize(AX));
}
print(&printer);
}
}
示例12: initLeds
void RayDisplayScene::initLeds()
{
QList<int> sizes;
//sizes << 64 << 40 << 64 << 40;
sizes << 48 << 32 << 48 << 32;
Q_ASSERT(4 == sizes.size());
QVector<QVector<QPointF>> sidedReceiversPos;
QVector<QVector<QPointF>> sidedSendersPos;
sidedReceiversPos.resize(sizes.size());
mSidedReceivers.resize(sizes.size());
sidedSendersPos.resize(sizes.size());
int allReceivers = 0;
for (int i = 0; i < sizes.size(); i++) {
Q_ASSERT(sizes.at(i) % 8 == 0);
sidedReceiversPos[i].reserve(sizes.at(i));
mSidedReceivers[i].reserve(sizes.at(i));
sidedSendersPos[i].reserve(sizes.at(i) / 8);
allReceivers += sizes.at(i) / 8;
}
mReceivers.reserve(allReceivers * 8);
mSenders.reserve(allReceivers);
// top left-to-right
for (int i = 0; i < sizes.at(0); i++) {
QGraphicsEllipseItem *r;
const int x = i * 10;
const int y = 0;
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2));
const int sideId = 0;
const QPointF p(x, y);
sidedReceiversPos[sideId] << p;
r->setPos(p);
mReceivers.append(r);
mSidedReceivers[sideId] << r;
}
// right top-to-bottom
for (int i = 0; i < sizes.at(1); i++) {
QGraphicsEllipseItem *r;
const int x = sizes.at(0) * 10;
const int y = i * 10 - (0 - 5);
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2));
const int sideId = 1;
const QPointF p(x, y);
sidedReceiversPos[sideId] << p;
r->setPos(p);
mReceivers.append(r);
mSidedReceivers[sideId] << r;
}
// bottom right-to-left
for (int i = 0; i < sizes.at(2); i++) {
QGraphicsEllipseItem *r;
const int x = i * -10 + sizes.at(0) * 10 - 10;
const int y = sizes.at(1) * 10;
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2));
const int sideId = 2;
const QPointF p(x, y);
sidedReceiversPos[sideId] << p;
r->setPos(p);
mReceivers.append(r);
mSidedReceivers[sideId] << r;
}
// left bottom-to-top
for (int i = 0; i < sizes.at(3); i++) {
QGraphicsEllipseItem *r;
const int x = -5;
const int y = i * -10 + ((sizes.at(1)) * 10 - 5);
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2));
const int sideId = 3;
const QPointF p(x, y);
sidedReceiversPos[sideId] << p;
r->setPos(p);
mReceivers.append(r);
mSidedReceivers[sideId] << r;
}
// top left-to-right
for (int i = 0; i < (sizes.at(0) / 8); i++) {
QGraphicsEllipseItem *r;
const int x = i * 80 + 35;
const int y = 0;
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2));
const int sideId = 0;
const QPointF p(x, y);
sidedSendersPos[sideId] << p;
r->setPos(p);
mSenders.append(Sender{r, 270, sideId});
}
// right top-to-bottom
for (int i = 0; i < (sizes.at(1) / 8); i++) {
QGraphicsEllipseItem *r;
const int x = sizes.at(0) * 10;
const int y = i * 80 - (0 - 40);
r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2));
const int sideId = 1;
const QPointF p(x, y);
sidedSendersPos[sideId] << p;
r->setPos(p);
mSenders.append(Sender{r, 180, sideId});
}
// bottom right-to-left
//.........这里部分代码省略.........
示例13: generate
QString GeneratorSetDylan::generate() {
// Code generation
QList<Generator *> generators;
LibraryGenerator *libraryGenerator = new LibraryGenerator;
LidGenerator *lidGenerator = new LidGenerator;
DylanGenerator *dylan_generator = 0;
PlainCppHeaderGenerator *cpp_header_generator = 0;
PlainCppImplGenerator *cpp_impl_generator = 0;
QStringList contexts;
dylan_generator = new DylanGenerator(libraryGenerator, lidGenerator);
if (!javaOutDir.isNull())
dylan_generator->setDylanOutputDirectory(javaOutDir);
if (!outDir.isNull())
dylan_generator->setLogOutputDirectory(outDir);
generators << dylan_generator;
contexts << "DylanGenerator";
cpp_header_generator = new PlainCppHeaderGenerator(lidGenerator);
if (!cppOutDir.isNull())
cpp_header_generator->setCppOutputDirectory(cppOutDir);
generators << cpp_header_generator;
contexts << "PlainCppHeaderGenerator";
cpp_impl_generator = new PlainCppImplGenerator(lidGenerator);
if (!cppOutDir.isNull())
cpp_impl_generator->setCppOutputDirectory(cppOutDir);
generators << cpp_impl_generator;
contexts << "PlainCppImplGenerator";
if (!cppOutDir.isNull())
lidGenerator->setCppOutputDirectory(cppOutDir);
generators << lidGenerator;
contexts << "LidGenerator";
if (!cppOutDir.isNull())
libraryGenerator->setOutputDirectory(cppOutDir);
generators << libraryGenerator;
contexts << "LibraryGenerator";
for (int i = 0; i < generators.size(); ++i) {
Generator *generator = generators.at(i);
ReportHandler::setContext(contexts.at(i));
if (generator->outputDirectory().isNull())
generator->setOutputDirectory(outDir);
generator->setClasses(builder.classes());
if (printStdout)
generator->printClasses();
else
generator->generate();
}
QString res;
res = QString("Classes in typesystem: %1\n"
"Generated:\n"
" - dylan.....: %2 (%3)\n"
" - cpp-impl..: %4 (%5)\n"
" - cpp-h.....: %6 (%7)\n"
" - library...: %8 (%9)\n"
" - lid.......: %10 (%11)\n"
)
.arg(builder.classes().size())
.arg(dylan_generator ? dylan_generator->numGenerated() : 0)
.arg(dylan_generator ? dylan_generator->numGeneratedAndWritten() : 0)
.arg(cpp_impl_generator ? cpp_impl_generator->numGenerated() : 0)
.arg(cpp_impl_generator ? cpp_impl_generator->numGeneratedAndWritten() : 0)
.arg(cpp_header_generator ? cpp_header_generator->numGenerated() : 0)
.arg(cpp_header_generator ? cpp_header_generator->numGeneratedAndWritten() : 0)
.arg(libraryGenerator->numGenerated())
.arg(libraryGenerator->numGeneratedAndWritten())
.arg(lidGenerator->numGenerated())
.arg(lidGenerator->numGeneratedAndWritten());
return res;
}
示例14: file
RenderOptionsDialog::RenderOptionsDialog()
: QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
{
setWindowOpacity(0.75);
setWindowTitle(tr("Options (double click to flip)"));
QGridLayout *layout = new QGridLayout;
setLayout(layout);
layout->setColumnStretch(1, 1);
int row = 0;
QCheckBox *check = new QCheckBox(tr("Dynamic cube map"));
check->setCheckState(Qt::Unchecked);
// Dynamic cube maps are only enabled when multi-texturing and render to texture are available.
check->setEnabled(glActiveTexture && glGenFramebuffersEXT);
connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int)));
layout->addWidget(check, 0, 0, 1, 2);
++row;
QPalette palette;
// Load all .par files
// .par files have a simple syntax for specifying user adjustable uniform variables.
QSet<QByteArray> uniforms;
QList<QString> filter = QStringList("*.par");
QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
foreach (QFileInfo fileInfo, files) {
QFile file(fileInfo.absoluteFilePath());
if (file.open(QIODevice::ReadOnly)) {
while (!file.atEnd()) {
QList<QByteArray> tokens = file.readLine().simplified().split(' ');
QList<QByteArray>::const_iterator it = tokens.begin();
if (it == tokens.end())
continue;
QByteArray type = *it;
if (++it == tokens.end())
continue;
QByteArray name = *it;
bool singleElement = (tokens.size() == 3); // type, name and one value
char counter[10] = "000000000";
int counterPos = 8; // position of last digit
while (++it != tokens.end()) {
m_parameterNames << name;
if (!singleElement) {
m_parameterNames.back() += "[";
m_parameterNames.back() += counter + counterPos;
m_parameterNames.back() += "]";
int j = 8; // position of last digit
++counter[j];
while (j > 0 && counter[j] > '9') {
counter[j] = '0';
++counter[--j];
}
if (j < counterPos)
counterPos = j;
}
if (type == "color") {
layout->addWidget(new QLabel(m_parameterNames.back()));
bool ok;
ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1);
m_parameterEdits << colorEdit;
layout->addWidget(colorEdit);
connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int)));
++row;
} else if (type == "float") {
layout->addWidget(new QLabel(m_parameterNames.back()));
bool ok;
FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1);
m_parameterEdits << floatEdit;
layout->addWidget(floatEdit);
connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int)));
++row;
}
}
示例15: main
int main(int argc, char *argv[])
{
QCoreApplication application(argc, argv);
const QStringList &args(application.arguments());
const bool quickMode(args.contains(QStringLiteral("-q")) || args.contains(QStringLiteral("--quick")));
QMap<QString, QString> parameters;
parameters.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false"));
QContactManager manager(QString::fromLatin1("org.nemomobile.contacts.sqlite"), parameters);
QContactFetchRequest request;
request.setManager(&manager);
// Perform an initial request to ensure the database has been created before we start timing
request.start();
request.waitForFinished();
qint64 elapsedTimeTotal = 0;
QElapsedTimer asyncTotalTimer;
asyncTotalTimer.start();
// Fetch all, no optimization hints
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Skip relationships
QContactFetchHint hint;
hint.setOptimizationHints(QContactFetchHint::NoRelationships);
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Reduce data access
hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type);
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Reduce number of results
hint.setMaxCountHint(request.contacts().count() / 8);
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Max count fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
qint64 asyncTotalElapsed = asyncTotalTimer.elapsed();
// Time some synchronous operations. First, generate the test data.
qsrand((int)asyncTotalElapsed);
QList<int> nbrContacts;
if (quickMode) {
nbrContacts << 200;
} else {
nbrContacts << 10 << 100 << 500 << 1000 << 2000;
}
QList<QList<QContact> > testData;
qDebug() << "\n\nGenerating test data for timings...";
for (int i = 0; i < nbrContacts.size(); ++i) {
int howMany = nbrContacts.at(i);
QList<QContact> newTestData;
newTestData.reserve(howMany);
//.........这里部分代码省略.........