当前位置: 首页>>代码示例>>C++>>正文


C++ QWebElementCollection::at方法代码示例

本文整理汇总了C++中QWebElementCollection::at方法的典型用法代码示例。如果您正苦于以下问题:C++ QWebElementCollection::at方法的具体用法?C++ QWebElementCollection::at怎么用?C++ QWebElementCollection::at使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QWebElementCollection的用法示例。


在下文中一共展示了QWebElementCollection::at方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: downloadedMangaList

void MangaherePlugin::downloadedMangaList(bool ok)
{
    if(!ok)
    {
        qDebug() << tr("There was an error loading the manga list from host 'www.mangahere.co'.");
        return;
    }

    //MangaList successfully downloaded, processing the HTML...

    m_mangaListLoaded = true;
    m_mangaList.clear();

    QWebElement element = m_pPageMangaList.mainFrame()->documentElement();
    QWebElementCollection collAllMangas = element.findAll(".manga_info");

    qDebug() << "Sample Manga:" << collAllMangas.at(0).toPlainText() << " url(" << collAllMangas.at(0).attribute("href", "ERROR") << ")";

    int i = 0;
    foreach (QWebElement oneManga, collAllMangas) {
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
        Manga::Simple manga;
        manga.title = oneManga.toPlainText();
        manga.url = oneManga.attribute("href", "ERROR");
        m_mangaList << manga;
        i++;
    }
开发者ID:Haellsigh,项目名称:Yamr-plugins,代码行数:27,代码来源:Mangahere.cpp

示例2: scrap

void dilbert::scrap(bool ok)
{
    if (ok)
    {
        ui->progressBar->hide();
        QWebElementCollection imgs = view->page()->mainFrame()->findAllElements("img");
        QWebElement img;
        if (comicid == latest || comicid == QDate(1989, 04, 16))
            img = imgs.at(1);
        else
            img = imgs.at(2);
        QString imgLink = QString("http://dilbert.com").append(img.attribute("src").toAscii().constData());
        ui->webView->setUrl(QUrl(imgLink));
        if (comicid == QDate(1989, 04, 16))
        {
            ui->prev->setEnabled(false);
        }
        else
        {
            ui->prev->setEnabled(true);
        }
        if (comicid == latest)
        {
            ui->next->setEnabled(false);
        }
        else
        {
            ui->next->setEnabled(true);
        }
    }
}
开发者ID:dhruvbhutani,项目名称:komedia,代码行数:31,代码来源:dilbert.cpp

示例3: parseSearchProductPage

//void ArestShopPlugin::SinglePageFound()
//{
//#ifdef USE_WEBKIT
//	QWebFrame * ptrFrame = getWebPage()->mainFrame();
//	parseProductPage(m_stCompData);
//	m_stCompData.strCompURL = ptrFrame->url().toString();
//	emit priceSearchedFinished(m_stCompData);
//	productFoundFinish();
//#endif
//};
void ArestShopPlugin::parseSearchProductPage(SearchResult & stResult,bool & bNextPage)
{
	//run XML search page parse

	bNextPage=false;
#ifdef USE_WEBKIT
	QWebFrame * ptrFrame = getWebPage()->mainFrame();
	//////////////////////////////////////////////////////////////////////////
	QWebElementCollection tableProdRows = ptrFrame->findAllElements("table[class=pricelist]");
	
	for(int iIndex=0;iIndex<tableProdRows.count();++iIndex)
	{
		QWebElement prodNameHeader = tableProdRows.at(iIndex).findFirst("td[class=nazwa]");
		if (prodNameHeader.isNull())
			continue;
		QWebElement productLink = prodNameHeader.findFirst("a");
		QUrl stProductURL = productLink.attribute("href");
		//////////////////////////////////////////////////////////////////////////
		QString strName = productLink.toPlainText();
		stResult.insert(std::make_pair(strName,stProductURL));
	}
	//////////////////////////////////////////////////////////////////////////
	QWebElement tablePageNavi = ptrFrame->findFirstElement("li[class=next]");
	if (tablePageNavi.isNull())
	{
		bNextPage=false;
		return;
	}
	bNextPage=true;
#endif
	stResult.insert(Arest::mSearchResult.begin(),Arest::mSearchResult.end());
	bNextPage=m_bLoadNextPage;
}
开发者ID:T4ng10r,项目名称:ComputerComponentsShop,代码行数:43,代码来源:ArestShop.cpp

示例4: updateBlockedPageElements

void QtWebKitWebPage::updateBlockedPageElements(const QStringList domainList, const bool isException)
{
	for (int i = 0; i < domainList.count(); ++i)
	{
		const QList<QString> exceptionList = isException ? ContentBlockingManager::getHidingRulesExceptions().values(domainList.at(i)) : ContentBlockingManager::getSpecificDomainHidingRules().values(domainList.at(i));

		for (int j = 0; j < exceptionList.count(); ++j)
		{
			const QWebElementCollection elements = mainFrame()->documentElement().findAll(exceptionList.at(j));

			for (int k = 0; k < elements.count(); ++k)
			{
				QWebElement element = elements.at(k);

				if (element.isNull())
				{
					continue;
				}

				if (isException)
				{
					element.setStyleProperty(QLatin1String("display"), QLatin1String("block"));
				}
				else
				{
					element.removeFromDocument();
				}
			}
		}
	}
}
开发者ID:mboevink,项目名称:otter,代码行数:31,代码来源:QtWebKitWebPage.cpp

示例5: setTargetBlank

void PhpWebView::setTargetBlank()
{
	QWebElementCollection coll = page()->mainFrame()->documentElement().findAll("a");
	for (int i=0; i<coll.count(); i++)
		coll.at(i).setAttribute("target", "_blank");

	QWebElementCollection coll2 = page()->mainFrame()->documentElement().findAll("form");
	for (int i=0; i<coll2.count(); i++)
		coll2.at(i).setAttribute("target", "_blank");
}
开发者ID:scraperlab,项目名称:browserext,代码行数:10,代码来源:phpwebview.cpp

示例6: foreach

    foreach (QWebElement selectField, selectFields) {
        QString name = selectField.attribute(QLatin1String("name"));
        int selectedIndex = selectField.evaluateJavaScript(QLatin1String("this.selectedIndex")).toInt();
        if (selectedIndex == -1)
            continue;

        QWebElementCollection options = selectField.findAll(QLatin1String("option"));
        QString value = options.at(selectedIndex).toPlainText();
        searchUrl.addQueryItem(name, value);
    }
开发者ID:mariuz,项目名称:fram,代码行数:10,代码来源:webview.cpp

示例7: LocationBarPopup

RSSWidget::RSSWidget(WebView* view, QWidget* parent)
    : LocationBarPopup(parent)
    , ui(new Ui::RSSWidget)
    , m_view(view)
{
    ui->setupUi(this);

    QWebEngineFrame* frame = m_view->page()->mainFrame();
    QWebElementCollection links = frame->findAllElements("link[type=\"application/rss+xml\"]");

    // Make sure RSS feeds fit into a window, in case there is a lot of feeds from one page
    // See #906
    int cols = links.count() / 10 == 0 ? 1 : links.count() / 10;
    int row = 0;

    for (int i = 0; i < links.count(); i++) {
        QWebElement element = links.at(i);
        QString title = element.attribute("title");
        const QUrl url = QUrl::fromEncoded(element.attribute("href").toUtf8());
        if (url.isEmpty()) {
            continue;
        }

        if (title.isEmpty()) {
            title = tr("Untitled feed");
        }

        QPushButton* button = new QPushButton(this);
        button->setIcon(QIcon(":icons/other/feed.png"));
        button->setStyleSheet("text-align:left");
        button->setText(title);
        button->setProperty("rss-url", url);
        button->setProperty("rss-title", title);

        if (!isRssFeedAlreadyStored(url)) {
            button->setFlat(true);
            button->setToolTip(url.toString());
        }
        else {
            button->setFlat(false);
            button->setEnabled(false);
            button->setToolTip(tr("You already have this feed."));
        }

        int pos = i % cols > 0 ? (i % cols) * 2 : 0;

        ui->gridLayout->addWidget(button, row, pos);
        connect(button, SIGNAL(clicked()), this, SLOT(addRss()));

        if (i % cols == cols - 1) {
            row++;
        }
    }
}
开发者ID:DmitriK,项目名称:qupzilla,代码行数:54,代码来源:rsswidget.cpp

示例8: loadFinished

void Browser::loadFinished(bool ok) {
    QUrl current_url(page->currentFrame()->baseUrl());

    // events trottling
    if (current_url == this->last_url)
    {
        qDebug() << this << QString("%1, loadFinished trottled.").arg(QDateTime::currentDateTime().toTime_t());
        return;
    }

    this->last_url = current_url;

    qDebug() << this << QString("%1, '%2', %3 ms.").arg(QDateTime::currentDateTime().toTime_t()).arg(current_url.toString()).arg(page_load_time.elapsed());

    if (!ok) {
        emit(errorHappened(page_load_time.elapsed(), page->currentFrame()->baseUrl()));
        restartTest(QString("its not ok, something wrong happened! (possibly 500) URL: %1").arg(page->currentFrame()->baseUrl().toString()));
        return;
     }

    QWebElement document= page->currentFrame()->documentElement();

    if (page->currentFrame()->baseUrl().host() != base_url.host())
    {
       restartTest("We've got outside the test site. Restarting.");
       return;
    }


    QWebElementCollection collection = document.findAll("a[href]");
    QWebElement link; QString link_href;

    if (collection.count() == 0)
    {
        restartTest("No links found on page. Restarting.");
        return;
    }

    // Ignoring javascript and empty links
    do
    {
       link = collection.at(qrand()%collection.count());
       link_href = link.attribute("href");
    }
    while ((link_href.count() == 0) || (link_href.at(0) == '#') || (link_href.contains("javascript:;")));

    emit(pageLoaded(page_load_time.elapsed(), page->currentFrame()->baseUrl()));

    link.evaluateJavaScript("var evObj = document.createEvent('MouseEvents');evObj.initEvent( 'click', true, true );this.dispatchEvent(evObj);");

    page_load_time.start();
    timeout_countdown->start();
}
开发者ID:brain-geek,项目名称:toad,代码行数:53,代码来源:browser.cpp

示例9: QFrame

RSSDetectionWidget::RSSDetectionWidget(WebView* view, QWidget* parent)
  : QFrame(parent, Qt::Popup)
  , view_(view)
{
  setAttribute(Qt::WA_DeleteOnClose);
  setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
  setLineWidth(1);
  setMidLineWidth(2);

  gridLayout_ = new QGridLayout(this);
  gridLayout_->setMargin(5);
  gridLayout_->setSpacing(5);

  QWebFrame* frame = view_->page()->mainFrame();
  QWebElementCollection links = frame->findAllElements("link[type=\"application/rss+xml\"]");

  int cols = links.count() / 10 == 0 ? 1 : links.count() / 10;
  int row = 0;

  for (int i = 0; i < links.count(); i++) {
    QWebElement element = links.at(i);
    QString title = element.attribute("title");
    const QUrl url = QUrl::fromEncoded(element.attribute("href").toUtf8());
    if (url.isEmpty()) {
      continue;
    }

    if (title.isEmpty()) {
      title = tr("Untitled feed");
    }

    QPushButton* button = new QPushButton(this);
    button->setStyleSheet("QPushButton {text-align:left; border: none; padding: 0px;}"
                          "QPushButton:hover {color: #1155CC;}");
    button->setCursor(Qt::PointingHandCursor);
    button->setText(title);
    button->setToolTip(url.toString());
    button->setProperty("rss-url", url);
    button->setProperty("rss-title", title);

    int pos = i % cols > 0 ? (i % cols) * 2 : 0;

    gridLayout_->addWidget(button, row, pos);
    connect(button, SIGNAL(clicked()), this, SLOT(addRss()));

    if (i % cols == cols - 1) {
      row++;
    }
  }
}
开发者ID:efferre79,项目名称:quiterss,代码行数:50,代码来源:rssdetectionwidget.cpp

示例10: setRadioCheckedProperty

void MarbleLegendBrowser::setRadioCheckedProperty( const QString& value, const QString& name , bool checked )
{
#ifndef MARBLE_NO_WEBKIT
    QWebElement box = page()->mainFrame()->findFirstElement("input[value="+value+']');
    QWebElementCollection boxes = page()->mainFrame()->findAllElements("input[name="+name+']');
    QString currentValue="";
    for(int i=0; i<boxes.count(); ++i) {
        currentValue = boxes.at(i).attribute("value");
        d->m_checkBoxMap[currentValue]=false;
        emit toggledShowProperty( currentValue, false );
    }
    if (!box.isNull()) {
        if (checked != d->m_checkBoxMap[value]) {
            d->m_checkBoxMap[value] = checked;
            emit toggledShowProperty( value, checked );
        }
    }

    update();
#endif
}
开发者ID:RaphaelCojocaru,项目名称:marble,代码行数:21,代码来源:MarbleLegendBrowser.cpp

示例11: modifyTags

/*
  This will go through and modify some of the ENML tags and turn
  them into HTML tags.  Things like en-media & en-crypt have no
  HTML values, so we turn them into HTML.
  */
void NoteFormatter::modifyTags(QWebPage &doc) {
    tempFiles.clear();

    // Modify en-media tags
    QLOG_TRACE() << "Searching for all en-media tags;";
    QWebElementCollection anchors = doc.mainFrame()->findAllElements("en-media");
    QLOG_TRACE() << "Search complete: " << anchors.toList().size();
    foreach (QWebElement enmedia, anchors) {
        if (enmedia.hasAttribute("type")) {
            QString attr = enmedia.attribute("type");
            QString hash = enmedia.attribute("hash");
            QStringList type = attr.split("/");
            if (type.size() >= 2) {
                QString appl = type[1];
                QLOG_TRACE() << "En-Media tag type: " << type[0];
                if (type[0] == "image")
                    modifyImageTags(enmedia, hash);
                else
                    modifyApplicationTags(enmedia, hash, appl);
                QLOG_TRACE() << "Type modified";
            }
        }
    }

    // Modify todo tags
    anchors = doc.mainFrame()->findAllElements("en-todo");
    qint32 enTodoCount = anchors.count();
    for (qint32 i=enTodoCount-1; i>=0; i--) {
            QWebElement enmedia = anchors.at(i);
            modifyTodoTags(enmedia);
    }

    anchors = doc.mainFrame()->findAllElements("en-crypt");
    qint32 enCryptLen = anchors.count();
    for (qint32 i=enCryptLen-1; i>=0; i--) {
        QWebElement enmedia = anchors.at(i);
        QString hint = enmedia.attribute("hint");
        QString cipher = enmedia.attribute("cipher", "RC2");
        QString length = enmedia.attribute("length","64");

        enmedia.setAttribute("contentEditable","false");
        enmedia.setAttribute("src", QString("file://")+global.fileManager.getImageDirPath("encrypt.png"));
        enmedia.setAttribute("en-tag","en-crypt");
        enmedia.setAttribute("cipher", cipher);
        enmedia.setAttribute("length", length);
        enmedia.setAttribute("hint", hint);
        enmedia.setAttribute("alt", enmedia.toInnerXml());
        global.cryptCounter++;
        enmedia.setAttribute("id", "crypt"+QString().number(global.cryptCounter));
        QString encryptedText = enmedia.toInnerXml();

        // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
        if (encryptedText.endsWith("\n"))
                encryptedText.truncate(encryptedText.length()-1);
        if (encryptedText.endsWith("\r"))
                encryptedText.truncate(encryptedText.length()-1);

        // Add the commands
        hint = hint.replace("'","&apos;");
        enmedia.setAttribute("onClick", "window.browserWindow.decryptText('crypt"+
                             QString().number(global.cryptCounter)+
                             "', '"+encryptedText+"', '"+
                             hint +"', '" +
                             cipher+ "', " +
                             length +
                             ");");
        enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
        enmedia.setInnerXml("");
        QString k = enmedia.toOuterXml();
        k.replace("<en-crypt", "<img");
        k.replace("img>", "<en-crypt");
        enmedia.setOuterXml(k);
    }


    // Modify link tags
    anchors = doc.mainFrame()->findAllElements("a");
    enCryptLen = anchors.count();
    for (qint32 i=0; i<anchors.count(); i++) {
        QWebElement element = anchors.at(i);
        if (!element.attribute("href").toLower().startsWith("latex://"))
            element.setAttribute("title", element.attribute("href"));
        else {
            element.setAttribute("title", element.attribute("title").toLower().replace("http://latex.codecogs.com/gif.latex?",""));
        }
    }

}
开发者ID:Hexcles,项目名称:Nixnote2,代码行数:93,代码来源:noteformatter.cpp

示例12: render

void Printer::render(int Pages = 0)
{
	// keep original preferences
	QPointer<ProfileWidget2> profile = MainWindow::instance()->graphics();
	int profileFrameStyle = profile->frameStyle();
	int animationOriginal = prefs.animation_speed;
	double fontScale = profile->getFontPrintScale();
	double printFontScale = 1.0;

	// apply printing settings to profile
	profile->setFrameStyle(QFrame::NoFrame);
	profile->setPrintMode(true, !printOptions->color_selected);
	profile->setToolTipVisibile(false);
	prefs.animation_speed = 0;

	// render the Qwebview
	QPainter painter;
	QRect viewPort(0, 0, pageSize.width(), pageSize.height());
	painter.begin(paintDevice);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);

	// get all refereces to diveprofile class in the Html template
	QWebElementCollection collection = webView->page()->mainFrame()->findAllElements(".diveprofile");

	QSize originalSize = profile->size();
	if (collection.count() > 0) {
		printFontScale = (double)collection.at(0).geometry().size().height() / (double)profile->size().height();
		profile->resize(collection.at(0).geometry().size());
	}
	profile->setFontPrintScale(printFontScale);

	int elemNo = 0;
	for (int i = 0; i < Pages; i++) {
		// render the base Html template
		webView->page()->mainFrame()->render(&painter, QWebFrame::ContentsLayer);

		// render all the dive profiles in the current page
		while (elemNo < collection.count() && collection.at(elemNo).geometry().y() < viewPort.y() + viewPort.height()) {
			// dive id field should be dive_{{dive_no}} se we remove the first 5 characters
			QString diveIdString = collection.at(elemNo).attribute("id");
			int diveId = diveIdString.remove(0, 5).toInt(0, 10);
			putProfileImage(collection.at(elemNo).geometry(), viewPort, &painter, get_dive_by_uniq_id(diveId), profile);
			elemNo++;
		}

		// scroll the webview to the next page
		webView->page()->mainFrame()->scroll(0, pageSize.height());
		viewPort.adjust(0, pageSize.height(), 0, pageSize.height());

		// rendering progress is 4/5 of total work
		emit(progessUpdated((i * 80.0 / Pages) + done));
		if (i < Pages - 1 && printMode == Printer::PRINT)
			static_cast<QPrinter*>(paintDevice)->newPage();
	}
	painter.end();

	// return profle settings
	profile->setFrameStyle(profileFrameStyle);
	profile->setPrintMode(false);
	profile->setFontPrintScale(fontScale);
	profile->setToolTipVisibile(true);
	profile->resize(originalSize);
	prefs.animation_speed = animationOriginal;

	//replot the dive after returning the settings
	profile->plotDive(0, true);
}
开发者ID:ngdmcc,项目名称:subsurface,代码行数:68,代码来源:printer.cpp

示例13: triggerAction

void QtWebKitWebWidget::triggerAction(WindowAction action, bool checked)
{
	const QWebPage::WebAction webAction = mapAction(action);

	if (webAction != QWebPage::NoWebAction)
	{
		m_webView->triggerPageAction(webAction, checked);

		return;
	}

	switch (action)
	{
		case RewindBackAction:
			m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(0));

			break;
		case RewindForwardAction:
			m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(m_webView->page()->history()->count() - 1));

			break;
		case CopyAddressAction:
			QApplication::clipboard()->setText(getUrl().toString());

			break;
		case ZoomInAction:
			setZoom(qMin((getZoom() + 10), 10000));

			break;
		case ZoomOutAction:
			setZoom(qMax((getZoom() - 10), 10));

			break;
		case ZoomOriginalAction:
			setZoom(100);

			break;
		case ReloadOrStopAction:
			if (isLoading())
			{
				triggerAction(StopAction);
			}
			else
			{
				triggerAction(ReloadAction);
			}

			break;
		case OpenLinkInNewTabAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), false, false);
			}

			break;
		case OpenLinkInNewTabBackgroundAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), true, false);
			}

			break;
		case OpenLinkInNewWindowAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), false, true);
			}

			break;
		case OpenLinkInNewWindowBackgroundAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), true, true);
			}

			break;
		case BookmarkLinkAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedAddBookmark(m_hitResult.linkUrl(), m_hitResult.element().attribute(QLatin1String("title")));
			}

			break;
		case OpenSelectionAsLinkAction:
			emit requestedOpenUrl(m_webView->selectedText(), false, false);

			break;
		case ImagePropertiesAction:
			{
				ImagePropertiesDialog dialog(m_hitResult.imageUrl(), m_hitResult.element().attribute(QLatin1String("alt")), m_hitResult.element().attribute(QLatin1String("longdesc")), m_hitResult.pixmap(), (m_networkAccessManager->cache() ? m_networkAccessManager->cache()->data(m_hitResult.imageUrl()) : NULL), this);
				QEventLoop eventLoop;

				m_parent->showDialog(&dialog);

				connect(&dialog, SIGNAL(finished(int)), &eventLoop, SLOT(quit()));
				connect(this, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));

				eventLoop.exec();

				m_parent->hideDialog(&dialog);
//.........这里部分代码省略.........
开发者ID:Kermit,项目名称:otter,代码行数:101,代码来源:QtWebKitWebWidget.cpp

示例14: completePage

void AutoFillModel::completePage(WebPage* page)
{
    if (!page) {
        return;
    }

    QUrl pageUrl = page->url();
    if (!isStored(pageUrl)) {
        return;
    }

    QWebElementCollection inputs;
    QList<QWebFrame*> frames;
    frames.append(page->mainFrame());
    while (!frames.isEmpty()) {
        QWebFrame* frame = frames.takeFirst();
        inputs.append(frame->findAllElements("input"));
        frames += frame->childFrames();
    }

    QString server = pageUrl.host();
    if (server.isEmpty()) {
        server = pageUrl.toString();
    }

    QSqlQuery query;
    query.prepare("SELECT data FROM autofill WHERE server=?");
    query.addBindValue(server);
    query.exec();
    query.next();
    QByteArray data = query.value(0).toByteArray();
    if (data.isEmpty()) {
        return;
    }

    // Why not to use encodedQueryItems = QByteArrays ?
    // Because we need to filter "+" characters that must be spaces
    // (not real "+" characters "%2B")

    QueryItems arguments = QUrl::fromEncoded("http://bla.com/?" + data).queryItems();
    for (int i = 0; i < arguments.count(); i++) {
        QString key = arguments.at(i).first;
        QString value = arguments.at(i).second;
        key.replace("+", " ");
        value.replace("+", " ");

        key = QUrl::fromEncoded(key.toUtf8()).toString();
        value = QUrl::fromEncoded(value.toUtf8()).toString();

        for (int i = 0; i < inputs.count(); i++) {
            QWebElement element = inputs.at(i);

            if (element.attribute("type") != "text" && element.attribute("type") != "password" && element.attribute("type") != "") {
                continue;
            }
            if (key == element.attribute("name")) {
                element.setAttribute("value", value);
            }
        }
    }
}
开发者ID:Shadowmeph,项目名称:QupZilla,代码行数:61,代码来源:autofillmodel.cpp

示例15: defaultFilePath

void WebPage::handleBase64Download(QWebFrame* pWebFrame, QUrl url)
{
    // look for beginning of base64 data
    QString base64 = QString::fromUtf8("base64,");
    int pos = url.path().indexOf(base64);
    if (pos == -1)
    {
        LOG_ERROR_MESSAGE("Base64 designator not found in data url");
        return;
    }

    // extract the base64 data from the uri
    QString base64Data = url.path();
    base64Data.remove(0, pos + base64.length());
    QByteArray base64ByteArray(base64Data.toStdString().c_str());
    QByteArray byteArray = QByteArray::fromBase64(base64ByteArray);

    // find the a tag in the page with this href
    QWebElement aTag;
    QString urlString = url.toString(QUrl::None);
    QWebElementCollection aElements = pWebFrame->findAllElements(
                                          QString::fromUtf8("a"));
    for (int i=0; i<aElements.count(); i++)
    {
        QWebElement a = aElements.at(i);
        QString href = a.attribute(QString::fromUtf8("href"));
        href.replace(QChar::fromAscii('\n'), QString::fromUtf8(""));
        if (href == urlString)
        {
            aTag = a;
            break;
        }
    }

    // if no a tag was found then bail
    if (aTag.isNull())
    {
        LOG_ERROR_MESSAGE("Unable to finding matching a tag for data url");
        return;
    }

    // get the download attribute (default filename)
    QString download = aTag.attribute(QString::fromUtf8("download"));
    QString defaultFilename = defaultSaveDir_.absoluteFilePath(download);

    // prompt for filename
    QString filename = QFileDialog::getSaveFileName(
                           NULL,
                           tr("Download File"),
                           defaultFilename,
                           defaultSaveDir_.absolutePath(),
                           0,
                           standardFileDialogOptions());
    if (!filename.isEmpty())
    {
        // see if we need to force the extension
        FilePath defaultFilePath(defaultFilename.toUtf8().constData());
        FilePath chosenFilePath(filename.toUtf8().constData());
        if (chosenFilePath.extension().empty() &&
                !defaultFilePath.extension().empty())
        {
            filename += QString::fromStdString(defaultFilePath.extension());
        }

        // write the file
        QFile file(filename);
        if (file.open(QIODevice::WriteOnly))
        {
            if (file.write(byteArray) == -1)
            {
                showFileError(QString::fromUtf8("writing"),
                              filename,
                              file.errorString());
            }

            file.close();
        }
        else
        {
            showFileError(QString::fromUtf8("writing"),
                          filename,
                          file.errorString());
        }

        // persist the defaultSaveDir
        defaultSaveDir_ = QFileInfo(file).dir();
    }
}
开发者ID:James-Arnold,项目名称:rstudio,代码行数:88,代码来源:DesktopWebPage.cpp


注:本文中的QWebElementCollection::at方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。