Commit 9b709335 authored by Pierre Rossi's avatar Pierre Rossi Committed by The Qt Project
Browse files

Import fancybrowser example


Change-Id: Ia61fbe3ef6b76c7530d10d4a3305d4208b3469ef
Reviewed-by: default avatarZeno Albisser <zeno.albisser@digia.com>
Showing with 524 additions and 0 deletions
......@@ -16,6 +16,7 @@ moc_*.cpp
.rcc
*nanobrowser
examples/widgets/browser/browser
examples/widgets/fancybrowser/fancybrowser
tests/widgets/qwebenginehistoryinterface/tst_qwebenginehistoryinterface
tests/widgets/qwebenginehistory/tst_qwebenginehistory
tests/widgets/qwebengineinspector/tst_qwebengineinspector
......
......@@ -4,5 +4,6 @@ SUBDIRS += quick/quicknanobrowser
qtHaveModule(widgets) {
SUBDIRS += \
widgets/browser \
widgets/fancybrowser \
widgets/widgetsnanobrowser
}
examples/widgets/fancybrowser/doc/images/fancybrowser-example.png

95.7 KB

/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Free Documentation License Usage
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of
** this file. Please review the following information to ensure
** the GNU Free Documentation License version 1.3 requirements
** will be met: http://www.gnu.org/copyleft/fdl.html.
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\example webkitwidgets/fancybrowser
\title Fancy Browser Example
\brief Demonstrates how to use browse web and manipulate content
\ingroup webkit-widgetexamples
\brief The Fancy Browser example shows how to use JQuery with QtWebKit to
create a web browser with special effects and content
manipulation.
\image fancybrowser-example.png
The application makes use of QWebFrame::evaluateJavaScript to
evaluate the jQuery JavaScript code. A QMainWindow with a QWebView
as central widget builds up the browser itself.
\section1 MainWindow Class Definition
The \c MainWindow class inherits QMainWindow. It implements a number of
slots to perform actions on both the application and on the web content.
\snippet webkitwidgets/fancybrowser/mainwindow.h 1
We also declare a QString that contains the jQuery, a QWebView
that displays the web content, and a QLineEdit that acts as the
address bar.
\section1 MainWindow Class Implementation
We start by implementing the constructor.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 1
The first part of the constructor sets the value of \c progress to
0. This value will be used later in the code to visualize the
loading of a webpage.
Next, the jQuery library is loaded using a QFile and reading the file
content. The jQuery library is a JavaScript library that provides different
functions for manipulating HTML.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 2
The second part of the constructor creates a QWebView and connects
slots to the views signals. Furthermore, we create a QLineEdit as
the browsers address bar. We then set the horizontal QSizePolicy
to fill the available area in the browser at all times. We add the
QLineEdit to a QToolbar together with a set of navigation actions
from QWebView::pageAction.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 3
The third and last part of the constructor implements two QMenus and assigns
a set of actions to them. The last line sets the QWebView as the central
widget in the QMainWindow.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 4
When the page is loaded, \c adjustLocation() updates the address
bar; \c adjustLocation() is triggered by the \c loadFinished()
signal in QWebView. In \c changeLocation() we create a QUrl
object, and then use it to load the page into the QWebView. When
the new web page has finished loading, \c adjustLocation() will be
run once more to update the address bar.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 5
\c adjustTitle() sets the window title and displays the loading
progress. This slot is triggered by the \c titleChanged() signal
in QWebView.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 6
When a web page has loaded, \c finishLoading() is triggered by the
\c loadFinished() signal in QWebView. \c finishLoading() then updates the
progress in the title bar and calls \c evaluateJavaScript() to evaluate the
jQuery library. This evaluates the JavaScript against the current web page.
What that means is that the JavaScript can be viewed as part of the content
loaded into the QWebView, and therefore needs to be loaded every time a new
page is loaded. Once the jQuery library is loaded, we can start executing
the different jQuery functions in the browser.
The rotateImages() function is then called explicitely to make sure
that the images of the newly loaded page respect the state of the toggle
action.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 7
The first jQuery-based function, \c highlightAllLinks(), is designed to
highlight all links in the current webpage. The JavaScript code looks
for web elements named \e {a}, which is the tag for a hyperlink.
For each such element, the background color is set to be yellow by
using CSS.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 8
The \c rotateImages() function rotates the images on the current
web page. Webkit supports CSS transforms and this JavaScript code
looks up all \e {img} elements and rotates the images 180 degrees
and then back again.
\snippet webkitwidgets/fancybrowser/mainwindow.cpp 9
The remaining four methods remove different elements from the current web
page. \c removeGifImages() removes all GIF images on the page by looking up
the \e {src} attribute of all the elements on the web page. Any element with
a \e {gif} file as its source is removed. \c removeInlineFrames() removes all
\e {iframe} or inline elements. \c removeObjectElements() removes all
\e {object} elements, and \c removeEmbeddedElements() removes any elements
such as plugins embedded on the page using the \e {embed} tag.
*/
QT += webenginewidgets
HEADERS = mainwindow.h
SOURCES = main.cpp \
mainwindow.cpp
RESOURCES = jquery.qrc
# install
#target.path = $$[QT_INSTALL_EXAMPLES]/webkitwidgets/fancybrowser
#INSTALLS += target
This diff is collapsed.
<RCC>
<qresource prefix="/" >
<file>jquery.min.js</file>
</qresource>
</RCC>
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
#include "mainwindow.h"
int main(int argc, char * argv[])
{
QApplication app(argc, argv);
QUrl url;
if (argc > 1)
url = QUrl::fromUserInput(argv[1]);
else
url = QUrl("http://www.google.com/ncr");
MainWindow *browser = new MainWindow(url);
browser->show();
return app.exec();
}
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
#include <QtNetwork>
#include <QtWebKitWidgets>
#include "mainwindow.h"
//! [1]
MainWindow::MainWindow(const QUrl& url)
{
progress = 0;
QFile file;
file.setFileName(":/jquery.min.js");
file.open(QIODevice::ReadOnly);
jQuery = file.readAll();
jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
file.close();
//! [1]
QNetworkProxyFactory::setUseSystemConfiguration(true);
//! [2]
view = new QWebView(this);
view->load(url);
connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
locationEdit = new QLineEdit(this);
locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy());
connect(locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation()));
QToolBar *toolBar = addToolBar(tr("Navigation"));
toolBar->addAction(view->pageAction(QWebPage::Back));
toolBar->addAction(view->pageAction(QWebPage::Forward));
toolBar->addAction(view->pageAction(QWebPage::Reload));
toolBar->addAction(view->pageAction(QWebPage::Stop));
toolBar->addWidget(locationEdit);
//! [2]
QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
QAction* viewSourceAction = new QAction("Page Source", this);
connect(viewSourceAction, SIGNAL(triggered()), SLOT(viewSource()));
viewMenu->addAction(viewSourceAction);
//! [3]
QMenu *effectMenu = menuBar()->addMenu(tr("&Effect"));
effectMenu->addAction("Highlight all links", this, SLOT(highlightAllLinks()));
rotateAction = new QAction(this);
rotateAction->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
rotateAction->setCheckable(true);
rotateAction->setText(tr("Turn images upside down"));
connect(rotateAction, SIGNAL(toggled(bool)), this, SLOT(rotateImages(bool)));
effectMenu->addAction(rotateAction);
QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
toolsMenu->addAction(tr("Remove GIF images"), this, SLOT(removeGifImages()));
toolsMenu->addAction(tr("Remove all inline frames"), this, SLOT(removeInlineFrames()));
toolsMenu->addAction(tr("Remove all object elements"), this, SLOT(removeObjectElements()));
toolsMenu->addAction(tr("Remove all embedded elements"), this, SLOT(removeEmbeddedElements()));
setCentralWidget(view);
setUnifiedTitleAndToolBarOnMac(true);
}
//! [3]
void MainWindow::viewSource()
{
QWebFrame *mainFrame = view->page()->mainFrame();
QTextEdit* textEdit = new QTextEdit(NULL);
textEdit->setAttribute(Qt::WA_DeleteOnClose);
textEdit->adjustSize();
textEdit->move(this->geometry().center() - textEdit->rect().center());
textEdit->setPlainText(mainFrame->toHtml());
textEdit->show();
}
//! [4]
void MainWindow::adjustLocation()
{
locationEdit->setText(view->url().toString());
}
void MainWindow::changeLocation()
{
QUrl url = QUrl::fromUserInput(locationEdit->text());
view->load(url);
view->setFocus();
}
//! [4]
//! [5]
void MainWindow::adjustTitle()
{
if (progress <= 0 || progress >= 100)
setWindowTitle(view->title());
else
setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress));
}
void MainWindow::setProgress(int p)
{
progress = p;
adjustTitle();
}
//! [5]
//! [6]
void MainWindow::finishLoading(bool)
{
progress = 100;
adjustTitle();
view->page()->mainFrame()->evaluateJavaScript(jQuery);
rotateImages(rotateAction->isChecked());
}
//! [6]
//! [7]
void MainWindow::highlightAllLinks()
{
// We append '; undefined' after the jQuery call here to prevent a possible recursion loop and crash caused by
// the way the elements returned by the each iterator elements reference each other, which causes problems upon
// converting them to QVariants.
QString code = "qt.jQuery('a').each( function () { qt.jQuery(this).css('background-color', 'yellow') } ); undefined";
view->page()->mainFrame()->evaluateJavaScript(code);
}
//! [7]
//! [8]
void MainWindow::rotateImages(bool invert)
{
QString code;
// We append '; undefined' after each of the jQuery calls here to prevent a possible recursion loop and crash caused by
// the way the elements returned by the each iterator elements reference each other, which causes problems upon
// converting them to QVariants.
if (invert)
code = "qt.jQuery('img').each( function () { qt.jQuery(this).css('-webkit-transition', '-webkit-transform 2s'); qt.jQuery(this).css('-webkit-transform', 'rotate(180deg)') } ); undefined";
else
code = "qt.jQuery('img').each( function () { qt.jQuery(this).css('-webkit-transition', '-webkit-transform 2s'); qt.jQuery(this).css('-webkit-transform', 'rotate(0deg)') } ); undefined";
view->page()->mainFrame()->evaluateJavaScript(code);
}
//! [8]
//! [9]
void MainWindow::removeGifImages()
{
QString code = "qt.jQuery('[src*=gif]').remove()";
view->page()->mainFrame()->evaluateJavaScript(code);
}
void MainWindow::removeInlineFrames()
{
QString code = "qt.jQuery('iframe').remove()";
view->page()->mainFrame()->evaluateJavaScript(code);
}
void MainWindow::removeObjectElements()
{
QString code = "qt.jQuery('object').remove()";
view->page()->mainFrame()->evaluateJavaScript(code);
}
void MainWindow::removeEmbeddedElements()
{
QString code = "qt.jQuery('embed').remove()";
view->page()->mainFrame()->evaluateJavaScript(code);
}
//! [9]
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
class QWebView;
QT_BEGIN_NAMESPACE
class QLineEdit;
QT_END_NAMESPACE
//! [1]
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(const QUrl& url);
protected slots:
void adjustLocation();
void changeLocation();
void adjustTitle();
void setProgress(int p);
void finishLoading(bool);
void viewSource();
void highlightAllLinks();
void rotateImages(bool invert);
void removeGifImages();
void removeInlineFrames();
void removeObjectElements();
void removeEmbeddedElements();
private:
QString jQuery;
QWebView *view;
QLineEdit *locationEdit;
QAction *rotateAction;
int progress;
//! [1]
};
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment