本文整理汇总了C++中QVector::isEmpty方法的典型用法代码示例。如果您正苦于以下问题:C++ QVector::isEmpty方法的具体用法?C++ QVector::isEmpty怎么用?C++ QVector::isEmpty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QVector
的用法示例。
在下文中一共展示了QVector::isEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: loadData
void QmlProfilerStatisticsModel::loadData(qint64 rangeStart, qint64 rangeEnd)
{
clear();
qint64 qmlTime = 0;
qint64 lastEndTime = 0;
QHash <int, QVector<qint64> > durations;
const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);
const QVector<QmlProfilerDataModel::QmlEventData> &eventList
= d->modelManager->qmlModel()->getEvents();
const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList
= d->modelManager->qmlModel()->getEventTypes();
// used by binding loop detection
QStack<const QmlProfilerDataModel::QmlEventData*> callStack;
callStack.push(0); // artificial root
for (int i = 0; i < eventList.size(); ++i) {
const QmlProfilerDataModel::QmlEventData *event = &eventList[i];
const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex()];
if (!d->acceptedTypes.contains(type->rangeType))
continue;
if (checkRanges) {
if ((event->startTime() + event->duration() < rangeStart)
|| (event->startTime() > rangeEnd))
continue;
}
// update stats
QmlEventStats *stats = &d->data[event->typeIndex()];
stats->duration += event->duration();
stats->durationSelf += event->duration();
if (event->duration() < stats->minTime)
stats->minTime = event->duration();
if (event->duration() > stats->maxTime)
stats->maxTime = event->duration();
stats->calls++;
// for median computing
durations[event->typeIndex()].append(event->duration());
// qml time computation
if (event->startTime() > lastEndTime) { // assume parent event if starts before last end
qmlTime += event->duration();
lastEndTime = event->startTime() + event->duration();
}
//
// binding loop detection
//
const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top();
while (potentialParent && !(potentialParent->startTime() + potentialParent->duration() >
event->startTime())) {
callStack.pop();
potentialParent = callStack.top();
}
// check whether event is already in stack
for (int ii = 1; ii < callStack.size(); ++ii) {
if (callStack.at(ii)->typeIndex() == event->typeIndex()) {
d->eventsInBindingLoop.insert(event->typeIndex());
break;
}
}
if (callStack.count() > 1)
d->data[callStack.top()->typeIndex()].durationSelf -= event->duration();
callStack.push(event);
d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2);
}
// post-process: calc mean time, median time, percentoftime
int i = d->data.size();
int total = i * 2;
for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) {
QmlEventStats* stats = &it.value();
if (stats->calls > 0)
stats->timePerCall = stats->duration / (double)stats->calls;
QVector<qint64> eventDurations = durations[it.key()];
if (!eventDurations.isEmpty()) {
Utils::sort(eventDurations);
stats->medianTime = eventDurations.at(eventDurations.count()/2);
}
stats->percentOfTime = stats->duration * 100.0 / qmlTime;
stats->percentSelf = stats->durationSelf * 100.0 / qmlTime;
d->modelManager->modelProxyCountUpdated(d->modelId, i++, total);
}
// set binding loop flag
foreach (int typeIndex, d->eventsInBindingLoop)
d->data[typeIndex].isBindingLoop = true;
//.........这里部分代码省略.........
示例2: event
bool GoForwardActionWidget::event(QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick || event->type() == QEvent::Wheel)
{
QList<GesturesManager::GesturesContext> contexts;
contexts << GesturesManager::ToolBarGesturesContext << GesturesManager::GenericGesturesContext;
if (GesturesManager::startGesture(this, event, contexts))
{
return true;
}
}
if (event->type() == QEvent::ContextMenu)
{
QContextMenuEvent *contextMenuEvent(static_cast<QContextMenuEvent*>(event));
if (contextMenuEvent)
{
if (contextMenuEvent->reason() == QContextMenuEvent::Mouse)
{
contextMenuEvent->accept();
return true;
}
event->accept();
Window *window(getWindow());
QMenu menu(this);
menu.addAction(window ? window->getContentsWidget()->getAction(ActionsManager::ClearTabHistoryAction) : ActionsManager::getAction(ActionsManager::ClearTabHistoryAction, this));
menu.addAction(window ? window->getContentsWidget()->getAction(ActionsManager::PurgeTabHistoryAction) : ActionsManager::getAction(ActionsManager::PurgeTabHistoryAction, this));
ToolBarWidget *toolBar = qobject_cast<ToolBarWidget*>(parentWidget());
if (toolBar)
{
menu.addSeparator();
menu.addActions(ToolBarWidget::createCustomizationMenu(toolBar->getIdentifier(), QList<QAction*>(), &menu)->actions());
}
menu.exec(contextMenuEvent->globalPos());
return true;
}
return false;
}
if (event->type() == QEvent::ToolTip)
{
QHelpEvent *helpEvent(dynamic_cast<QHelpEvent*>(event));
if (helpEvent)
{
const QVector<QKeySequence> shortcuts(ActionsManager::getActionDefinition(ActionsManager::GoForwardAction).shortcuts);
QString toolTip(text() + (shortcuts.isEmpty() ? QString() : QLatin1String(" (") + shortcuts.at(0).toString(QKeySequence::NativeText) + QLatin1Char(')')));
if (getWindow())
{
const WindowHistoryInformation history(getWindow()->getContentsWidget()->getHistory());
if (!history.entries.isEmpty() && history.index < (history.entries.count() - 1))
{
QString title(history.entries.at(history.index + 1).title);
title = (title.isEmpty() ? tr("(Untitled)") : title.replace(QLatin1Char('&'), QLatin1String("&&")));
toolTip = title + QLatin1String(" (") + text() + (shortcuts.isEmpty() ? QString() : QLatin1String(" - ") + shortcuts.at(0).toString(QKeySequence::NativeText)) + QLatin1Char(')');
}
}
QToolTip::showText(helpEvent->globalPos(), toolTip);
}
return true;
}
return ActionWidget::event(event);
}
示例3: if
// genExpressionElements(QString input)
// The parsing section of the calculator.
//
// Generates an QVector of expression elements from a QString input
// This QVector can then be processed to give a quantitative value.
QVector<ExpressionElement> StringCalculator::genExpressionElements(QString input)
{
// Declare our output vector, starting with size 0.
QVector<ExpressionElement> expressionVector = QVector<ExpressionElement>(0);
// Index that determines where to start when searching for the next operation
int crawlIndex = 0;
while(crawlIndex < input.length())
{
//--------------------------------------------------------------------------------------------------------------------------------
// Operation handling
//--------------------------------------------------------------------------------------------------------------------------------
// Check for operations
if(input.at(crawlIndex) == QChar('['))
{
int operationEnd = input.indexOf("]", crawlIndex);
// Is there a closing bracket?
if(operationEnd < 0)
{
// INTERNAL ERROR
// No closing bracket for operation
throw 103;
}
else
{
// Add a new expression element to the vector
expressionVector.append(ExpressionElement(input.mid(crawlIndex, operationEnd + 1 - crawlIndex)));
crawlIndex = operationEnd + 1;
continue;
}
}
//--------------------------------------------------------------------------------------------------------------------------------
// Subexpression handling
//--------------------------------------------------------------------------------------------------------------------------------
if(input.at(crawlIndex) == QChar('('))
{
// Turns out the below statement doesn't work.
//int subexpressionEnd = input.indexOf(")", crawlIndex);
int subexpressionEnd = crawlIndex+1; // A placeholder value for where the subexpression ends.
int subexpressionCounter = 1; // Counts how many subexpressions we need to end.
// Loop through the input, counting up all the open and close parens to find our matching one
int parenI = subexpressionEnd;
for(; parenI < input.size(); parenI++)
{
if(input.at(parenI) == QChar('('))
{
subexpressionCounter++;
}
else if(input.at(parenI) == QChar(')'))
{
subexpressionCounter--;
if(subexpressionCounter == 0)
{
// Stop incrementing parenI here.
break;
}
}
// We haven't found the close paren yet, increment parenI.
}
// We either found the closing paren or we didn't.
// Assign it the value of the loop iterator.
subexpressionEnd = parenI;
if(subexpressionEnd < 0)
{
subexpressionEnd = input.size();
}
double subexpressionNet = calculateQStringInput(input.mid(crawlIndex + 1, subexpressionEnd - 1 - crawlIndex));
// Support stuff like 5(10) = 50
if(!expressionVector.isEmpty())
{
if(expressionVector.at(expressionVector.size()-1).isNumber_)
{
expressionVector.append(ExpressionElement("[*]"));
}
}
expressionVector.append(ExpressionElement(subexpressionNet));
crawlIndex = subexpressionEnd + 1;
continue;
}
//--------------------------------------------------------------------------------------------------------------------------------
//.........这里部分代码省略.........
示例4: renderPrivate
void QWebFramePrivate::renderPrivate(QPainter *painter, QWebFrame::RenderLayer layer, const QRegion &clip)
{
if (!frame->view() || !frame->contentRenderer())
return;
QVector<QRect> vector = clip.rects();
if (vector.isEmpty())
return;
GraphicsContext context(painter);
if (context.paintingDisabled() && !context.updatingControlTints())
return;
WebCore::FrameView* view = frame->view();
view->layoutIfNeededRecursive();
for (int i = 0; i < vector.size(); ++i) {
const QRect& clipRect = vector.at(i);
QRect intersectedRect = clipRect.intersected(view->frameRect());
painter->save();
painter->setClipRect(clipRect, Qt::IntersectClip);
int x = view->x();
int y = view->y();
if (layer & QWebFrame::ContentsLayer) {
context.save();
int scrollX = view->scrollX();
int scrollY = view->scrollY();
QRect rect = intersectedRect;
context.translate(x, y);
rect.translate(-x, -y);
context.translate(-scrollX, -scrollY);
rect.translate(scrollX, scrollY);
context.clip(view->visibleContentRect());
view->paintContents(&context, rect);
context.restore();
}
if (layer & QWebFrame::ScrollBarLayer
&& !view->scrollbarsSuppressed()
&& (view->horizontalScrollbar() || view->verticalScrollbar())) {
context.save();
QRect rect = intersectedRect;
context.translate(x, y);
rect.translate(-x, -y);
view->paintScrollbars(&context, rect);
context.restore();
}
if (layer & QWebFrame::PanIconLayer)
view->paintPanScrollIcon(&context);
painter->restore();
}
}
示例5: retrieveDataInternal
int UIDnDHandler::retrieveDataInternal( Qt::DropAction dropAction,
const QString &strMIMEType,
QVector<uint8_t> &vecData)
{
LogFlowFunc(("Retrieving data as '%s', dropAction=%d\n", qPrintable(strMIMEType), dropAction));
int rc = VINF_SUCCESS;
/* Indicate to the guest that we have dropped the data on the host.
* The guest then will initiate the actual "drop" operation into our proxy on the guest. */
Assert(!m_dndSource.isNull());
CProgress progress = m_dndSource.Drop(strMIMEType,
UIDnDHandler::toVBoxDnDAction(dropAction));
LogFlowFunc(("Source: isOk=%RTbool\n", m_dndSource.isOk()));
if (m_dndSource.isOk())
{
/* Send a mouse event with released mouse buttons into the guest that triggers
* the "drop" event in our proxy window on the guest. */
AssertPtr(m_pSession);
m_pSession->mouse().PutMouseEvent(0, 0, 0, 0, 0);
msgCenter().showModalProgressDialog(progress,
tr("Retrieving data ..."), ":/progress_dnd_gh_90px.png",
m_pParent);
LogFlowFunc(("Progress: fCanceled=%RTbool, fCompleted=%RTbool, isOk=%RTbool, hrc=%Rhrc\n",
progress.GetCanceled(), progress.GetCompleted(), progress.isOk(), progress.GetResultCode()));
if (!progress.GetCanceled())
{
rc = ( progress.isOk()
&& progress.GetResultCode() == 0)
? VINF_SUCCESS : VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */
if (RT_SUCCESS(rc))
{
/* After we successfully retrieved data from the source we query it from Main. */
vecData = m_dndSource.ReceiveData(); /** @todo QVector.size() is "int" only!? */
if (m_dndSource.isOk())
{
if (vecData.isEmpty())
rc = VERR_NO_DATA;
}
else
{
msgCenter().cannotDropDataToHost(m_dndSource, m_pParent);
rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */
}
}
else
msgCenter().cannotDropDataToHost(progress, m_pParent);
}
else /* Don't pop up a message. */
rc = VERR_CANCELLED;
}
else
{
msgCenter().cannotDropDataToHost(m_dndSource, m_pParent);
rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */
}
setOpMode(DNDMODE_UNKNOWN);
LogFlowFuncLeaveRC(rc);
return rc;
}
示例6: constructQuery
PostingIterator* SearchStore::constructQuery(Transaction* tr, const Term& term)
{
Q_ASSERT(tr);
if (term.operation() == Term::And || term.operation() == Term::Or) {
QList<Term> subTerms = term.subTerms();
QVector<PostingIterator*> vec;
vec.reserve(subTerms.size());
for (const Term& t : term.subTerms()) {
vec << constructQuery(tr, t);
}
if (vec.isEmpty()) {
return 0;
}
if (term.operation() == Term::And) {
return new AndPostingIterator(vec);
} else {
return new OrPostingIterator(vec);
}
}
if (term.value().isNull()) {
return 0;
}
Q_ASSERT(term.value().isValid());
Q_ASSERT(term.comparator() != Term::Auto);
Q_ASSERT(term.comparator() == Term::Contains ? term.value().type() == QVariant::String : true);
const QVariant value = term.value();
const QByteArray property = term.property().toLower().toUtf8();
if (property == "type" || property == "kind") {
EngineQuery q = constructTypeQuery(value.toString());
return tr->postingIterator(q);
}
else if (property == "includefolder") {
const QByteArray folder = QFile::encodeName(value.toString());
Q_ASSERT(!folder.isEmpty());
Q_ASSERT(folder.startsWith('/'));
quint64 id = filePathToId(folder);
if (!id) {
qDebug() << "Folder" << value.toString() << "does not exist";
return 0;
}
return tr->docUrlIter(id);
}
else if (property == "modified" || property == "mtime") {
if (value.type() == QVariant::ByteArray) {
QByteArray ba = value.toByteArray();
Q_ASSERT(ba.size() >= 4);
int year = ba.mid(0, 4).toInt();
int month = ba.mid(4, 2).toInt();
int day = ba.mid(6, 2).toInt();
Q_ASSERT(year);
// uses 0 to represent whole month or whole year
month = month >= 0 && month <= 12 ? month : 0;
day = day >= 0 && day <= 31 ? day : 0;
QDate startDate(year, month ? month : 1, day ? day : 1);
QDate endDate(startDate);
if (month == 0) {
endDate.setDate(endDate.year(), 12, 31);
} else if (day == 0) {
endDate.setDate(endDate.year(), endDate.month(), endDate.daysInMonth());
}
return tr->mTimeRangeIter(QDateTime(startDate).toTime_t(), QDateTime(endDate, QTime(23, 59, 59)).toTime_t());
}
else if (value.type() == QVariant::Date || value.type() == QVariant::DateTime) {
const QDateTime dt = value.toDateTime();
return constructMTimeQuery(tr, dt, term.comparator());
}
else {
Q_ASSERT_X(0, "SearchStore::constructQuery", "modified property must contain date/datetime values");
}
}
else if (property == "rating") {
bool okay = false;
int rating = value.toInt(&okay);
if (!okay) {
qDebug() << "Rating comparisons must be with an integer";
return 0;
}
PostingDB::Comparator pcom;
if (term.comparator() == Term::Greater || term.comparator() == Term::GreaterEqual) {
pcom = PostingDB::GreaterEqual;
if (term.comparator() == Term::Greater && rating)
rating++;
}
//.........这里部分代码省略.........
示例7: cacheGlyphs
void QSymbianVGFontGlyphCache::cacheGlyphs(QVGPaintEnginePrivate *d,
QFontEngine *fontEngine,
const glyph_t *g, int count)
{
#ifdef QT_SYMBIAN_HARDWARE_GLYPH_CACHE
QFontEngineS60 *s60fontEngine = static_cast<QFontEngineS60*>(fontEngine);
if (s60fontEngine->m_activeFont->TypeUid() != KCFbsFontUid)
return QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count);
QVector<glyph_t> uncachedGlyphs;
while (count-- > 0) {
// Skip this glyph if we have already cached it before.
glyph_t glyph = *g++;
if (((glyph < 256) && ((cachedGlyphsMask[glyph / 32] & (1 << (glyph % 32))) != 0))
|| cachedGlyphs.contains(glyph))
continue;
if (!uncachedGlyphs.contains(glyph))
uncachedGlyphs.append(glyph);
}
if (!uncachedGlyphs.isEmpty()) {
CFbsFont *cfbsFont = static_cast<CFbsFont *>(s60fontEngine->m_activeFont);
RFbsGlyphDataIterator iter;
int err = iter.Open(*cfbsFont, (const unsigned int*)uncachedGlyphs.constData(), uncachedGlyphs.count());
if (err == KErrNotSupported || err == KErrInUse) { // Fallback in possibly supported error cases
iter.Close();
qWarning("Falling back to default QVGFontGlyphCache");
return QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count);
}
for (; err == KErrNone; err = iter.Next()) {
const unsigned int glyph = iter.GlyphCode();
const RSgImage& image = iter.Image();
const TOpenFontCharMetrics& metrics = iter.Metrics();
TRect glyphBounds;
metrics.GetHorizBounds(glyphBounds);
VGImage vgImage = sgImageToVGImage(0, image);
VGfloat origin[2];
VGfloat escapement[2];
origin[0] = -glyphBounds.iTl.iX;
origin[1] = glyphBounds.iBr.iY;
escapement[0] = 0;
escapement[1] = 0;
vgSetGlyphToImage(font, glyph, vgImage, origin, escapement);
vgDestroyImage(vgImage);
// Add to cache
if (glyph < 256)
cachedGlyphsMask[glyph / 32] |= (1 << (glyph % 32));
else
cachedGlyphs.insert(glyph);
}
iter.Close();
if (err == KErrNoMemory || err == KErrNoGraphicsMemory)
qWarning("Not enough memory to cache glyph");
else if (err != KErrNotFound)
qWarning("Received error %d from glyph cache", err);
}
#else
QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count);
#endif
}
示例8: do_find
//------------------------------------------------------------------------------
// Name: do_find
// Desc:
//------------------------------------------------------------------------------
void DialogReferences::do_find() {
bool ok = false;
edb::address_t address;
const edb::address_t page_size = edb::v1::debugger_core->page_size();
const QString text = ui->txtAddress->text();
if(!text.isEmpty()) {
ok = edb::v1::eval_expression(text, &address);
}
if(ok) {
edb::v1::memory_regions().sync();
const QList<IRegion::pointer> regions = edb::v1::memory_regions().regions();
int i = 0;
for(const IRegion::pointer ®ion: regions) {
// a short circut for speading things up
if(region->accessible() || !ui->chkSkipNoAccess->isChecked()) {
const edb::address_t page_count = region->size() / page_size;
const QVector<quint8> pages = edb::v1::read_pages(region->start(), page_count);
if(!pages.isEmpty()) {
const quint8 *p = &pages[0];
const quint8 *const pages_end = &pages[0] + region->size();
while(p != pages_end) {
if(pages_end - p < edb::v1::pointer_size()) {
break;
}
const edb::address_t addr = p - &pages[0] + region->start();
edb::address_t test_address(0);
memcpy(&test_address, p, edb::v1::pointer_size());
if(test_address == address) {
auto item = new QListWidgetItem(edb::v1::format_pointer(addr));
item->setData(TypeRole, 'D');
item->setData(AddressRole, addr);
ui->listWidget->addItem(item);
}
edb::Instruction inst(p, pages_end, addr);
if(inst) {
switch(inst.operation()) {
case edb::Instruction::Operation::X86_INS_MOV:
// instructions of the form: mov [ADDR], 0xNNNNNNNN
Q_ASSERT(inst.operand_count() == 2);
if(inst.operands()[0].general_type() == edb::Operand::TYPE_EXPRESSION) {
if(inst.operands()[1].general_type() == edb::Operand::TYPE_IMMEDIATE && static_cast<edb::address_t>(inst.operands()[1].immediate()) == address) {
auto item = new QListWidgetItem(edb::v1::format_pointer(addr));
item->setData(TypeRole, 'C');
item->setData(AddressRole, addr);
ui->listWidget->addItem(item);
}
}
break;
case edb::Instruction::Operation::X86_INS_PUSH:
// instructions of the form: push 0xNNNNNNNN
Q_ASSERT(inst.operand_count() == 1);
if(inst.operands()[0].general_type() == edb::Operand::TYPE_IMMEDIATE && static_cast<edb::address_t>(inst.operands()[0].immediate()) == address) {
auto item = new QListWidgetItem(edb::v1::format_pointer(addr));
item->setData(TypeRole, 'C');
item->setData(AddressRole, addr);
ui->listWidget->addItem(item);
}
break;
default:
if(is_jump(inst) || is_call(inst)) {
if(inst.operands()[0].general_type() == edb::Operand::TYPE_REL) {
if(inst.operands()[0].relative_target() == address) {
auto item = new QListWidgetItem(edb::v1::format_pointer(addr));
item->setData(TypeRole, 'C');
item->setData(AddressRole, addr);
ui->listWidget->addItem(item);
}
}
}
break;
}
}
Q_EMIT updateProgress(util::percentage(i, regions.size(), p - &pages[0], region->size()));
++p;
}
}
} else {
Q_EMIT updateProgress(util::percentage(i, regions.size()));
//.........这里部分代码省略.........
示例9: timerEvent
void DownloadManager::timerEvent(QTimerEvent* e)
{
QVector<QTime> remTimes;
QVector<int> progresses;
QVector<double> speeds;
if (e->timerId() == m_timer.timerId()) {
if (!ui->list->count()) {
ui->speedLabel->clear();
setWindowTitle(tr("Download Manager"));
#ifdef Q_OS_WIN
if (m_taskbarButton) {
m_taskbarButton->progress()->hide();
}
#endif
return;
}
for (int i = 0; i < ui->list->count(); i++) {
DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
if (!downItem || downItem->isCancelled() || !downItem->isDownloading()) {
continue;
}
progresses.append(downItem->progress());
remTimes.append(downItem->remainingTime());
speeds.append(downItem->currentSpeed());
}
if (remTimes.isEmpty()) {
return;
}
QTime remaining;
foreach (const QTime &time, remTimes) {
if (time > remaining) {
remaining = time;
}
}
int progress = 0;
foreach (int prog, progresses) {
progress += prog;
}
progress = progress / progresses.count();
double speed = 0.00;
foreach (double spee, speeds) {
speed += spee;
}
#ifndef Q_OS_WIN
ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()),
DownloadItem::currentSpeedToString(speed),
DownloadItem::remaingTimeToString(remaining)));
#endif
setWindowTitle(tr("%1% - Download Manager").arg(progress));
#ifdef Q_OS_WIN
if (m_taskbarButton) {
m_taskbarButton->progress()->show();
m_taskbarButton->progress()->setValue(progress);
}
#endif
}
QWidget::timerEvent(e);
}
示例10: updateCurve
void JCurveGroupWidget::updateCurve(JCurveWidget *curveView)
{
if (!curveView) {
return;
}
// 清空旧数据
curveView->clearCurve();
// 获取横、纵坐标信号量
const QString suffix = curveView->property("suffix").toString().replace('-', '_');
const QString nameX = curveView->property("nameX").toString();
const QString nameY = curveView->property("nameY").toString();
QString sectionX = nameX.section(" (", 0, 0);
QString sectionY = nameY.section(" (", 0, 0);
//
QString legendTitle = nameY % " (" % suffix % ")";
JCurveWidget::AxisXYType axisXYType = curveView->axisXYType();
// 获取M-H信号名称
QString machSection, heightSection;
if (!JFlyRecord::instance()->readSignalMHSection(
JSqlDataMgr::instance()->signalTableNamePrefix().append(suffix),
machSection, heightSection)) {
return;
}
// 生成数据表名称
const QString recordTableName =
JSqlDataMgr::instance()->recordTableNamePrefix().append(suffix);
//
if (axisXYType == JCurveWidget::AxisXY_Value_Value) {
// 获取记录数据
QVector<QPointF> data;
QListIterator<QRectF> citerSiftAreas(q_siftAreas);
while (citerSiftAreas.hasNext()) {
const QRectF &range = citerSiftAreas.next();
//
QVector<QPointF> tempData;
if (JSqlDataMgr::instance()->readRecordDataV(recordTableName, sectionX, sectionY,
machSection,
heightSection,
range, tempData)) {
data << tempData;
}
}
// 检测是否有数据需要处理
if (data.isEmpty()) {
return; // 无数据需要绘制
}
//
curveView->updateData(curveView->addCurve(legendTitle), data);
} else {
// 获取记录数据
if (axisXYType == JCurveWidget::AxisXY_Value_Time) {
qSwap(sectionX, sectionY);
}
//
QList<QPair<QTime, qreal> > data;
QListIterator<QRectF> citerSiftAreas(q_siftAreas);
while (citerSiftAreas.hasNext()) {
const QRectF &range = citerSiftAreas.next();
//
QList<QPair<QTime, qreal> > tempData;
if (JSqlDataMgr::instance()->readRecordDataV(recordTableName, sectionX, sectionY,
machSection,
heightSection,
range, tempData)) {
data.append(tempData);
}
}
// 检测是否有数据需要处理
if (data.isEmpty()) {
return; // 无数据需要绘制
}
//
curveView->updateData(curveView->addCurve(legendTitle), data);
}
}
示例11: handlePageLoaded
void QtWebEnginePage::handlePageLoaded(const QString &result)
{
if (m_widget)
{
const QVector<int> profiles(ContentBlockingManager::getProfileList(m_widget->getOption(QLatin1String("Content/BlockingProfiles"), url()).toStringList()));
if (!profiles.isEmpty())
{
const QStringList domainList(ContentBlockingManager::createSubdomainList(url().host()));
QStringList styleSheetBlackList(ContentBlockingManager::getStyleSheet(profiles));
QStringList styleSheetWhiteList;
for (int i = 0; i < domainList.count(); ++i)
{
styleSheetBlackList += ContentBlockingManager::getStyleSheetBlackList(domainList.at(i), profiles);
styleSheetWhiteList += ContentBlockingManager::getStyleSheetWhiteList(domainList.at(i), profiles);
}
QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/hideElements.js"));
if (file.open(QIODevice::ReadOnly))
{
runJavaScript(QString(file.readAll()).arg(createJavaScriptList(styleSheetWhiteList)).arg(createJavaScriptList(styleSheetBlackList)));
file.close();
}
}
const QStringList blockedRequests(qobject_cast<QtWebEngineWebBackend*>(m_widget->getBackend())->getBlockedElements(url().host()));
if (!blockedRequests.isEmpty())
{
QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/hideBlockedRequests.js"));
if (file.open(QIODevice::ReadOnly))
{
runJavaScript(QString(file.readAll()).arg(createJavaScriptList(blockedRequests)));
file.close();
}
}
}
QString string(url().toString());
string.truncate(1000);
const QRegularExpressionMatch match(QRegularExpression(QStringLiteral(">(<img style=\"-webkit-user-select: none;(?: cursor: zoom-in;)?\"|<video controls=\"\" autoplay=\"\" name=\"media\"><source) src=\"%1").arg(QRegularExpression::escape(string))).match(result));
const bool isViewingMedia(match.hasMatch());
if (isViewingMedia && match.captured().startsWith(QLatin1String("><img")))
{
settings()->setAttribute(QWebEngineSettings::AutoLoadImages, true);
settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/imageViewer.js"));
file.open(QIODevice::ReadOnly);
runJavaScript(file.readAll());
file.close();
}
if (isViewingMedia != m_isViewingMedia)
{
m_isViewingMedia = isViewingMedia;
emit viewingMediaChanged(m_isViewingMedia);
}
}
示例12: loadTile
const StackedTile* StackedTileLoader::loadTile( TileId const & stackedTileId )
{
// check if the tile is in the hash
d->m_cacheLock.lockForRead();
StackedTile * stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
d->m_cacheLock.unlock();
if ( stackedTile ) {
stackedTile->setUsed( true );
return stackedTile;
}
// here ends the performance critical section of this method
d->m_cacheLock.lockForWrite();
// has another thread loaded our tile due to a race condition?
stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
if ( stackedTile ) {
stackedTile->setUsed( true );
d->m_cacheLock.unlock();
return stackedTile;
}
mDebug() << "StackedTileLoader::loadTile" << stackedTileId.toString();
// the tile was not in the hash so check if it is in the cache
stackedTile = d->m_tileCache.take( stackedTileId );
if ( stackedTile ) {
stackedTile->setUsed( true );
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
d->m_cacheLock.unlock();
return stackedTile;
}
// tile (valid) has not been found in hash or cache, so load it from disk
// and place it in the hash from where it will get transferred to the cache
// mDebug() << "load Tile from Disk: " << stackedTileId.toString();
QVector<QSharedPointer<TextureTile> > tiles;
QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId );
QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const textureLayer = *pos;
TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(),
stackedTileId.x(), stackedTileId.y() );
mDebug() << "StackedTileLoader::loadTile: tile" << textureLayer->sourceDir()
<< tileId.toString() << textureLayer->tileSize();
const QImage tileImage = d->m_tileLoader->loadTile( tileId, DownloadBrowse );
const Blending *blending = d->m_blendingFactory.findBlending( textureLayer->blending() );
if ( blending == 0 && !textureLayer->blending().isEmpty() ) {
mDebug() << Q_FUNC_INFO << "could not find blending" << textureLayer->blending();
}
QSharedPointer<TextureTile> tile( new TextureTile( tileId, tileImage, blending ) );
tiles.append( tile );
}
Q_ASSERT( !tiles.isEmpty() );
const QImage resultImage = d->m_layerDecorator.merge( stackedTileId, tiles );
stackedTile = new StackedTile( stackedTileId, resultImage, tiles );
stackedTile->setUsed( true );
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
d->m_cacheLock.unlock();
return stackedTile;
}
示例13: QgsDebugMsg
QVector<QgsDataItem *> QgsWMSConnectionItem::createChildren()
{
QVector<QgsDataItem *> children;
QgsDataSourceUri uri;
uri.setEncodedUri( mUri );
QgsDebugMsg( "mUri = " + mUri );
QgsWmsSettings wmsSettings;
if ( !wmsSettings.parseUri( mUri ) )
{
children.append( new QgsErrorItem( this, tr( "Failed to parse WMS URI" ), mPath + "/error" ) );
return children;
}
bool res = mCapabilitiesDownload->downloadCapabilities( wmsSettings.baseUrl(), wmsSettings.authorization() );
if ( !res )
{
children.append( new QgsErrorItem( this, tr( "Failed to download capabilities" ), mPath + "/error" ) );
return children;
}
QgsWmsCapabilities caps;
if ( !caps.parseResponse( mCapabilitiesDownload->response(), wmsSettings.parserSettings() ) )
{
children.append( new QgsErrorItem( this, tr( "Failed to parse capabilities" ), mPath + "/error" ) );
return children;
}
// Attention: supportedLayers() gives tree leafs, not top level
QVector<QgsWmsLayerProperty> layerProperties = caps.supportedLayers();
if ( !layerProperties.isEmpty() )
{
QgsWmsCapabilitiesProperty capabilitiesProperty = caps.capabilitiesProperty();
const QgsWmsCapabilityProperty &capabilityProperty = capabilitiesProperty.capability;
for ( const QgsWmsLayerProperty &layerProperty : qgis::as_const( capabilityProperty.layers ) )
{
// Attention, the name may be empty
QgsDebugMsg( QString::number( layerProperty.orderId ) + ' ' + layerProperty.name + ' ' + layerProperty.title );
QString pathName = layerProperty.name.isEmpty() ? QString::number( layerProperty.orderId ) : layerProperty.name;
QgsWMSLayerItem *layer = new QgsWMSLayerItem( this, layerProperty.title, mPath + '/' + pathName, capabilitiesProperty, uri, layerProperty );
children << layer;
}
}
QList<QgsWmtsTileLayer> tileLayers = caps.supportedTileLayers();
if ( !tileLayers.isEmpty() )
{
QHash<QString, QgsWmtsTileMatrixSet> tileMatrixSets = caps.supportedTileMatrixSets();
const auto constTileLayers = tileLayers;
for ( const QgsWmtsTileLayer &l : constTileLayers )
{
QString title = l.title.isEmpty() ? l.identifier : l.title;
QgsDataItem *layerItem = l.styles.size() == 1 ? this : new QgsDataCollectionItem( this, title, mPath + '/' + l.identifier );
if ( layerItem != this )
{
layerItem->setCapabilities( layerItem->capabilities2() & ~QgsDataItem::Fertile );
layerItem->setState( QgsDataItem::Populated );
layerItem->setToolTip( title );
children << layerItem;
}
for ( const QgsWmtsStyle &style : qgis::as_const( l.styles ) )
{
QString styleName = style.title.isEmpty() ? style.identifier : style.title;
if ( layerItem == this )
styleName = title; // just one style so no need to display it
QgsDataItem *styleItem = l.setLinks.size() == 1 ? layerItem : new QgsDataCollectionItem( layerItem, styleName, layerItem->path() + '/' + style.identifier );
if ( styleItem != layerItem )
{
styleItem->setCapabilities( styleItem->capabilities2() & ~QgsDataItem::Fertile );
styleItem->setState( QgsDataItem::Populated );
styleItem->setToolTip( styleName );
if ( layerItem == this )
children << styleItem;
else
layerItem->addChildItem( styleItem );
}
for ( const QgsWmtsTileMatrixSetLink &setLink : qgis::as_const( l.setLinks ) )
{
QString linkName = setLink.tileMatrixSet;
if ( styleItem == layerItem )
linkName = styleName; // just one link so no need to display it
QgsDataItem *linkItem = l.formats.size() == 1 ? styleItem : new QgsDataCollectionItem( styleItem, linkName, styleItem->path() + '/' + setLink.tileMatrixSet );
if ( linkItem != styleItem )
{
linkItem->setCapabilities( linkItem->capabilities2() & ~QgsDataItem::Fertile );
linkItem->setState( QgsDataItem::Populated );
linkItem->setToolTip( linkName );
if ( styleItem == this )
children << linkItem;
//.........这里部分代码省略.........
示例14: startSync
void SyncEngine::startSync()
{
if (_journal->exists()) {
QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos();
if (!pollInfos.isEmpty()) {
qDebug() << "Finish Poll jobs before starting a sync";
CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account,
_journal, _localPath, this);
connect(job, SIGNAL(finished()), this, SLOT(startSync()));
connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString)));
job->start();
return;
}
}
Q_ASSERT(!_syncRunning);
_syncRunning = true;
Q_ASSERT(_csync_ctx);
if (!QDir(_localPath).exists()) {
// No _tr, it should only occur in non-mirall
emit csyncError("Unable to find local sync directory.");
finalize();
return;
}
_syncedItems.clear();
_syncItemMap.clear();
_needsUpdate = false;
csync_resume(_csync_ctx);
int fileRecordCount = -1;
if (!_journal->exists()) {
qDebug() << "=====sync looks new (no DB exists)";
} else {
qDebug() << "=====sync with existing DB";
}
qDebug() << "=====Using Qt" << qVersion();
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
qDebug() << "=====Using SSL library version"
<< QSslSocket::sslLibraryVersionString().toUtf8().data();
#endif
fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet
if( fileRecordCount == -1 ) {
qDebug() << "No way to create a sync journal!";
emit csyncError(tr("Unable to initialize a sync journal."));
finalize();
return;
// database creation error!
}
_csync_ctx->read_remote_from_db = true;
// This tells csync to never read from the DB if it is empty
// thereby speeding up the initial discovery significantly.
_csync_ctx->db_is_empty = (fileRecordCount == 0);
auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList);
bool usingSelectiveSync = (!selectiveSyncBlackList.isEmpty());
qDebug() << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync");
if (fileRecordCount >= 0 && fileRecordCount < 50 && !usingSelectiveSync) {
qDebug() << "===== Activating recursive PROPFIND (currently" << fileRecordCount << "file records)";
bool no_recursive_propfind = false;
csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind);
} else {
bool no_recursive_propfind = true;
csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind);
}
csync_set_userdata(_csync_ctx, this);
_account->credentials()->syncContextPreStart(_csync_ctx);
// csync_set_auth_callback( _csync_ctx, getauth );
//csync_set_log_level( 11 ); don't set the loglevel here, it shall be done by folder.cpp or owncloudcmd.cpp
int timeout = OwncloudPropagator::httpTimeout();
csync_set_module_property(_csync_ctx, "timeout", &timeout);
_stopWatch.start();
qDebug() << "#### Discovery start #################################################### >>";
_discoveryMainThread = new DiscoveryMainThread(account());
_discoveryMainThread->setParent(this);
connect(this, SIGNAL(finished()), _discoveryMainThread, SLOT(deleteLater()));
connect(_discoveryMainThread, SIGNAL(etagConcatenation(QString)), this, SLOT(slotRootEtagReceived(QString)));
DiscoveryJob *discoveryJob = new DiscoveryJob(_csync_ctx);
discoveryJob->_selectiveSyncBlackList = selectiveSyncBlackList;
discoveryJob->_selectiveSyncWhiteList =
_journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList);
discoveryJob->_newSharedFolderSizeLimit = _newSharedFolderSizeLimit;
discoveryJob->moveToThread(&_thread);
connect(discoveryJob, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int)));
connect(discoveryJob, SIGNAL(folderDiscovered(bool,QString)),
//.........这里部分代码省略.........
示例15: interceptRequest
void QtWebEngineUrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &request)
{
if (!m_contentBlockingProfiles.contains(request.firstPartyUrl().host()))
{
m_contentBlockingProfiles[request.firstPartyUrl().host()] = ContentBlockingManager::getProfileList(SettingsManager::getValue(QLatin1String("Content/BlockingProfiles"), request.firstPartyUrl()).toStringList());
}
const QVector<int> contentBlockingProfiles(m_contentBlockingProfiles.value(request.firstPartyUrl().host()));
if (contentBlockingProfiles.isEmpty())
{
const NetworkManagerFactory::DoNotTrackPolicy doNotTrackPolicy(NetworkManagerFactory::getDoNotTrackPolicy());
if (doNotTrackPolicy != NetworkManagerFactory::SkipTrackPolicy)
{
request.setHttpHeader(QStringLiteral("DNT").toLatin1(), ((doNotTrackPolicy == NetworkManagerFactory::DoNotAllowToTrackPolicy) ? QStringLiteral("1") : QStringLiteral("0")).toLatin1());
}
return;
}
ContentBlockingManager::ResourceType resourceType(ContentBlockingManager::OtherType);
switch (request.resourceType())
{
case QWebEngineUrlRequestInfo::ResourceTypeMainFrame:
resourceType = ContentBlockingManager::MainFrameType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeSubFrame:
resourceType = ContentBlockingManager::SubFrameType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeStylesheet:
resourceType = ContentBlockingManager::StyleSheetType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeScript:
resourceType = ContentBlockingManager::ScriptType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeImage:
resourceType = ContentBlockingManager::ImageType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeObject:
case QWebEngineUrlRequestInfo::ResourceTypeMedia:
resourceType = ContentBlockingManager::ObjectType;
break;
case QWebEngineUrlRequestInfo::ResourceTypeXhr:
resourceType = ContentBlockingManager::XmlHttpRequestType;
break;
default:
break;
}
const ContentBlockingManager::CheckResult result(ContentBlockingManager::checkUrl(contentBlockingProfiles, request.firstPartyUrl(), request.requestUrl(), resourceType));
if (result.isBlocked)
{
Console::addMessage(QCoreApplication::translate("main", "Blocked request"), Otter::NetworkMessageCategory, LogMessageLevel, request.requestUrl().toString(), -1);
request.block(true);
}
}