2 Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
3 Copyright (C) 2008 Holger Hans Peter Freyther
4 Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in>
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public License
17 along with this library; see the file COPYING.LIB. If not, write to
18 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
26 #include "QWebPageClient.h"
28 #include "qwebframe.h"
29 #include "qwebpage_p.h"
37 class QWebViewPrivate {
39 QWebViewPrivate(QWebView *view)
42 , renderHints(QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform)
47 virtual ~QWebViewPrivate();
49 void _q_pageDestroyed();
50 void detachCurrentPage();
55 QPainter::RenderHints renderHints;
58 QWebViewPrivate::~QWebViewPrivate()
63 void QWebViewPrivate::_q_pageDestroyed()
72 \brief The QWebView class provides a widget that is used to view and edit
78 QWebView is the main widget component of the QtWebKit web browsing module.
79 It can be used in various applications to display web content live from the
82 The image below shows QWebView previewed in \QD with a Nokia website.
84 \image qwebview-url.png
86 A web site can be loaded onto QWebView with the load() function. Like all
87 Qt widgets, the show() function must be invoked in order to display
88 QWebView. The snippet below illustrates this:
90 \snippet webkitsnippets/simple/main.cpp Using QWebView
92 Alternatively, setUrl() can also be used to load a web site. If you have
93 the HTML content readily available, you can use setHtml() instead.
95 The loadStarted() signal is emitted when the view begins loading. The
96 loadProgress() signal, on the other hand, is emitted whenever an element of
97 the web view completes loading, such as an embedded image, a script, etc.
98 Finally, the loadFinished() signal is emitted when the view has loaded
99 completely. It's argument - either \c true or \c false - indicates
100 load success or failure.
102 The page() function returns a pointer to the web page object. See
103 \l{Elements of QWebView} for an explanation of how the web page
104 is related to the view. To modify your web view's settings, you can access
105 the QWebSettings object with the settings() function. With QWebSettings,
106 you can change the default fonts, enable or disable features such as
107 JavaScript and plugins.
109 The title of an HTML document can be accessed with the title() property.
110 Additionally, a web site may also specify an icon, which can be accessed
111 using the icon() property. If the title or the icon changes, the corresponding
112 titleChanged() and iconChanged() signals will be emitted. The
113 textSizeMultiplier() property can be used to change the overall size of
114 the text displayed in the web view.
116 If you require a custom context menu, you can implement it by reimplementing
117 \l{QWidget::}{contextMenuEvent()} and populating your QMenu with the actions
118 obtained from pageAction(). More functionality such as reloading the view,
119 copying selected text to the clipboard, or pasting into the view, is also
120 encapsulated within the QAction objects returned by pageAction(). These
121 actions can be programmatically triggered using triggerPageAction().
122 Alternatively, the actions can be added to a toolbar or a menu directly.
123 QWebView maintains the state of the returned actions but allows
124 modification of action properties such as \l{QAction::}{text} or
127 A QWebView can be printed onto a QPrinter using the print() function.
128 This function is marked as a slot and can be conveniently connected to
129 \l{QPrintPreviewDialog}'s \l{QPrintPreviewDialog::}{paintRequested()}
132 If you want to provide support for web sites that allow the user to open
133 new windows, such as pop-up windows, you can subclass QWebView and
134 reimplement the createWindow() function.
136 \section1 Elements of QWebView
138 QWebView consists of other objects such as QWebFrame and QWebPage. The
139 flowchart below shows these elements are related.
141 \image qwebview-diagram.png
143 \note It is possible to use QWebPage and QWebFrame, without using QWebView,
144 if you do not require QWidget attributes. Nevertheless, QtWebKit depends
145 on QtGui, so you should use a QApplication instead of QCoreApplication.
147 \sa {Previewer Example}, {Web Browser}, {Form Extractor Example},
148 {Google Chat Example}, {Fancy Browser Example}
152 Constructs an empty QWebView with parent \a parent.
156 QWebView::QWebView(QWidget *parent)
159 d = new QWebViewPrivate(this);
161 #if !defined(Q_WS_QWS)
162 setAttribute(Qt::WA_InputMethodEnabled);
165 setAttribute(Qt::WA_AcceptTouchEvents);
166 setAcceptDrops(true);
168 setMouseTracking(true);
169 setFocusPolicy(Qt::WheelFocus);
173 Destroys the web view.
175 QWebView::~QWebView()
181 Returns a pointer to the underlying web page.
185 QWebPage *QWebView::page() const
188 QWebView *that = const_cast<QWebView *>(this);
189 that->setPage(new QWebPage(that));
194 void QWebViewPrivate::detachCurrentPage()
199 page->d->view.clear();
201 // if the page client is the special client constructed for
202 // delegating the responsibilities to a QWidget, we need
205 if (page->d->client && page->d->client->isQWidgetClient())
206 page->d->client.clear();
208 page->d->client.release();
210 // if the page was created by us, we own it and need to
211 // destroy it as well.
213 if (page->parent() == view)
216 page->disconnect(view);
222 Makes \a page the new web page of the web view.
224 The parent QObject of the provided page remains the owner
225 of the object. If the current page is a child of the web
226 view, it will be deleted.
230 void QWebView::setPage(QWebPage* page)
235 d->detachCurrentPage();
239 d->page->setView(this);
240 d->page->setPalette(palette());
241 // #### connect signals
242 QWebFrame *mainFrame = d->page->mainFrame();
243 connect(mainFrame, SIGNAL(titleChanged(QString)),
244 this, SIGNAL(titleChanged(QString)));
245 connect(mainFrame, SIGNAL(iconChanged()),
246 this, SIGNAL(iconChanged()));
247 connect(mainFrame, SIGNAL(urlChanged(QUrl)),
248 this, SIGNAL(urlChanged(QUrl)));
250 connect(d->page, SIGNAL(loadStarted()),
251 this, SIGNAL(loadStarted()));
252 connect(d->page, SIGNAL(loadProgress(int)),
253 this, SIGNAL(loadProgress(int)));
254 connect(d->page, SIGNAL(loadFinished(bool)),
255 this, SIGNAL(loadFinished(bool)));
256 connect(d->page, SIGNAL(statusBarMessage(QString)),
257 this, SIGNAL(statusBarMessage(QString)));
258 connect(d->page, SIGNAL(linkClicked(QUrl)),
259 this, SIGNAL(linkClicked(QUrl)));
260 connect(d->page, SIGNAL(selectionChanged()),
261 this, SIGNAL(selectionChanged()));
263 connect(d->page, SIGNAL(microFocusChanged()),
264 this, SLOT(updateMicroFocus()));
265 connect(d->page, SIGNAL(destroyed()),
266 this, SLOT(_q_pageDestroyed()));
268 setAttribute(Qt::WA_OpaquePaintEvent, d->page);
273 Loads the specified \a url and displays it.
275 \note The view remains the same until enough data has arrived to display the new \a url.
277 \sa setUrl(), url(), urlChanged(), QUrl::fromUserInput()
279 void QWebView::load(const QUrl &url)
281 page()->mainFrame()->load(url);
285 \fn void QWebView::load(const QNetworkRequest &request, QNetworkAccessManager::Operation operation, const QByteArray &body)
287 Loads a network request, \a request, using the method specified in \a operation.
289 \a body is optional and is only used for POST operations.
291 \note The view remains the same until enough data has arrived to display the new url.
293 \sa url(), urlChanged()
296 void QWebView::load(const QNetworkRequest &request,
297 QNetworkAccessManager::Operation operation,
298 const QByteArray &body)
300 page()->mainFrame()->load(request, operation, body);
304 Sets the content of the web view to the specified \a html.
306 External objects such as stylesheets or images referenced in the HTML
307 document are located relative to \a baseUrl.
309 The \a html is loaded immediately; external objects are loaded asynchronously.
311 When using this method, WebKit assumes that external resources such as
312 JavaScript programs or style sheets are encoded in UTF-8 unless otherwise
313 specified. For example, the encoding of an external script can be specified
314 through the charset attribute of the HTML script tag. Alternatively, the
315 encoding can also be specified by the web server.
317 This is a convenience function equivalent to setContent(html, "text/html", baseUrl).
319 \warning This function works only for HTML, for other mime types (i.e. XHTML, SVG)
320 setContent() should be used instead.
322 \sa load(), setContent(), QWebFrame::toHtml(), QWebFrame::setContent()
324 void QWebView::setHtml(const QString &html, const QUrl &baseUrl)
326 page()->mainFrame()->setHtml(html, baseUrl);
330 Sets the content of the web view to the specified content \a data. If the \a mimeType argument
331 is empty it is currently assumed that the content is HTML but in future versions we may introduce
334 External objects referenced in the content are located relative to \a baseUrl.
336 The \a data is loaded immediately; external objects are loaded asynchronously.
338 \sa load(), setHtml(), QWebFrame::toHtml()
340 void QWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl)
342 page()->mainFrame()->setContent(data, mimeType, baseUrl);
346 Returns a pointer to the view's history of navigated web pages.
350 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 0
352 QWebHistory *QWebView::history() const
354 return page()->history();
358 Returns a pointer to the view/page specific settings object.
362 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 1
364 \sa QWebSettings::globalSettings()
366 QWebSettings *QWebView::settings() const
368 return page()->settings();
372 \property QWebView::title
373 \brief the title of the web page currently viewed
375 By default, this property contains an empty string.
379 QString QWebView::title() const
382 return d->page->mainFrame()->title();
387 \property QWebView::url
388 \brief the url of the web page currently viewed
390 Setting this property clears the view and loads the URL.
392 By default, this property contains an empty, invalid URL.
394 \sa load(), urlChanged()
397 void QWebView::setUrl(const QUrl &url)
399 page()->mainFrame()->setUrl(url);
402 QUrl QWebView::url() const
405 return d->page->mainFrame()->url();
410 \property QWebView::icon
411 \brief the icon associated with the web page currently viewed
413 By default, this property contains a null icon.
415 \sa iconChanged(), QWebSettings::iconForUrl()
417 QIcon QWebView::icon() const
420 return d->page->mainFrame()->icon();
425 \property QWebView::hasSelection
426 \brief whether this page contains selected content or not.
428 By default, this property is false.
430 \sa selectionChanged()
432 bool QWebView::hasSelection() const
435 return d->page->hasSelection();
440 \property QWebView::selectedText
441 \brief the text currently selected
443 By default, this property contains an empty string.
445 \sa findText(), selectionChanged(), selectedHtml()
447 QString QWebView::selectedText() const
450 return d->page->selectedText();
456 \property QWebView::selectedHtml
457 \brief the HTML currently selected
459 By default, this property contains an empty string.
461 \sa findText(), selectionChanged(), selectedText()
463 QString QWebView::selectedHtml() const
466 return d->page->selectedHtml();
472 Returns a pointer to a QAction that encapsulates the specified web action \a action.
474 QAction *QWebView::pageAction(QWebPage::WebAction action) const
476 return page()->action(action);
481 Triggers the specified \a action. If it is a checkable action the specified
482 \a checked state is assumed.
484 The following example triggers the copy action and therefore copies any
485 selected text to the clipboard.
487 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 2
491 void QWebView::triggerPageAction(QWebPage::WebAction action, bool checked)
493 page()->triggerAction(action, checked);
497 \property QWebView::modified
498 \brief whether the document was modified by the user
500 Parts of HTML documents can be editable for example through the
501 \c{contenteditable} attribute on HTML elements.
503 By default, this property is false.
505 bool QWebView::isModified() const
508 return d->page->isModified();
513 Qt::TextInteractionFlags QWebView::textInteractionFlags() const
515 // ### FIXME (add to page)
516 return Qt::TextInteractionFlags();
521 \property QWebView::textInteractionFlags
522 \brief how the view should handle user input
524 Specifies how the user can interact with the text on the page.
528 void QWebView::setTextInteractionFlags(Qt::TextInteractionFlags flags)
531 // ### FIXME (add to page)
538 QSize QWebView::sizeHint() const
540 return QSize(800, 600); // ####...
544 \property QWebView::zoomFactor
546 \brief the zoom factor for the view
549 void QWebView::setZoomFactor(qreal factor)
551 page()->mainFrame()->setZoomFactor(factor);
554 qreal QWebView::zoomFactor() const
556 return page()->mainFrame()->zoomFactor();
560 \property QWebView::textSizeMultiplier
561 \brief the scaling factor for all text in the frame
564 Use setZoomFactor instead, in combination with the
565 ZoomTextOnly attribute in QWebSettings.
567 \note Setting this property also enables the
568 ZoomTextOnly attribute in QWebSettings.
570 By default, this property contains a value of 1.0.
574 Sets the value of the multiplier used to scale the text in a Web page to
575 the \a factor specified.
577 void QWebView::setTextSizeMultiplier(qreal factor)
579 page()->mainFrame()->setTextSizeMultiplier(factor);
583 Returns the value of the multiplier used to scale the text in a Web page.
585 qreal QWebView::textSizeMultiplier() const
587 return page()->mainFrame()->textSizeMultiplier();
591 \property QWebView::renderHints
593 \brief the default render hints for the view
595 These hints are used to initialize QPainter before painting the Web page.
597 QPainter::TextAntialiasing and QPainter::SmoothPixmapTransform are enabled by default.
599 \note This property is not available on Symbian. However, the getter and
600 setter functions can still be used directly.
602 \sa QPainter::renderHints()
607 Returns the render hints used by the view to render content.
609 \sa QPainter::renderHints()
611 QPainter::RenderHints QWebView::renderHints() const
613 return d->renderHints;
618 Sets the render hints used by the view to the specified \a hints.
620 \sa QPainter::setRenderHints()
622 void QWebView::setRenderHints(QPainter::RenderHints hints)
624 if (hints == d->renderHints)
626 d->renderHints = hints;
632 If \a enabled is true, enables the specified render \a hint; otherwise
635 \sa renderHints, QPainter::renderHints()
637 void QWebView::setRenderHint(QPainter::RenderHint hint, bool enabled)
639 QPainter::RenderHints oldHints = d->renderHints;
641 d->renderHints |= hint;
643 d->renderHints &= ~hint;
644 if (oldHints != d->renderHints)
650 Finds the specified string, \a subString, in the page, using the given \a options.
652 If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences
653 that exist in the page. All subsequent calls will extend the highlight, rather than
654 replace it, with occurrences of the new string.
656 If the HighlightAllOccurrences flag is not passed, the function will select an occurrence
657 and all subsequent calls will replace the current occurrence with the next one.
659 To clear the selection, just pass an empty string.
661 Returns true if \a subString was found; otherwise returns false.
663 \sa selectedText(), selectionChanged()
665 bool QWebView::findText(const QString &subString, QWebPage::FindFlags options)
668 return d->page->findText(subString, options);
674 bool QWebView::event(QEvent *e)
677 #ifndef QT_NO_CONTEXTMENU
678 if (e->type() == QEvent::ContextMenu) {
681 QContextMenuEvent *event = static_cast<QContextMenuEvent *>(e);
682 if (d->page->swallowContextMenuEvent(event)) {
686 d->page->updatePositionDependentActions(event->pos());
688 #endif // QT_NO_CONTEXTMENU
689 if (e->type() == QEvent::ShortcutOverride) {
692 } else if (e->type() == QEvent::CursorChange) {
693 // An unsetCursor will set the cursor to Qt::ArrowCursor.
694 // Thus this cursor change might be a QWidget::unsetCursor()
695 // If this is not the case and it came from WebCore, the
696 // QWebPageClient already has set its cursor internally
697 // to Qt::ArrowCursor, so updating the cursor is always
698 // right, as it falls back to the last cursor set by
700 // FIXME: Add a QEvent::CursorUnset or similar to Qt.
701 if (cursor().shape() == Qt::ArrowCursor)
702 d->page->d->client->resetCursor();
704 } else if (e->type() == QEvent::TouchBegin
705 || e->type() == QEvent::TouchEnd
706 || e->type() == QEvent::TouchUpdate) {
709 // Always return true so that we'll receive also TouchUpdate and TouchEnd events
711 } else if (e->type() == QEvent::Leave)
715 return QWidget::event(e);
719 Prints the main frame to the given \a printer.
721 \sa QWebFrame::print(), QPrintPreviewDialog
723 void QWebView::print(QPrinter *printer) const
725 #ifndef QT_NO_PRINTER
726 page()->mainFrame()->print(printer);
731 Convenience slot that stops loading the document.
735 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 3
737 \sa reload(), pageAction(), loadFinished()
739 void QWebView::stop()
742 d->page->triggerAction(QWebPage::Stop);
746 Convenience slot that loads the previous document in the list of documents
747 built by navigating links. Does nothing if there is no previous document.
751 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 4
753 \sa forward(), pageAction()
755 void QWebView::back()
758 d->page->triggerAction(QWebPage::Back);
762 Convenience slot that loads the next document in the list of documents
763 built by navigating links. Does nothing if there is no next document.
767 \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 5
769 \sa back(), pageAction()
771 void QWebView::forward()
774 d->page->triggerAction(QWebPage::Forward);
778 Reloads the current document.
780 \sa stop(), pageAction(), loadStarted()
782 void QWebView::reload()
785 d->page->triggerAction(QWebPage::Reload);
790 void QWebView::resizeEvent(QResizeEvent *e)
793 d->page->setViewportSize(e->size());
798 void QWebView::paintEvent(QPaintEvent *ev)
802 #ifdef QWEBKIT_TIME_RENDERING
807 QWebFrame *frame = d->page->mainFrame();
809 p.setRenderHints(d->renderHints);
811 frame->render(&p, ev->region());
813 #ifdef QWEBKIT_TIME_RENDERING
814 int elapsed = time.elapsed();
815 qDebug() << "paint event on " << ev->region() << ", took to render = " << elapsed;
820 This function is called from the createWindow() method of the associated QWebPage,
821 each time the page wants to create a new window of the given \a type. This might
822 be the result, for example, of a JavaScript request to open a document in a new window.
824 \note If the createWindow() method of the associated page is reimplemented, this
825 method is not called, unless explicitly done so in the reimplementation.
827 \note In the cases when the window creation is being triggered by JavaScript, apart from
828 reimplementing this method application must also set the JavaScriptCanOpenWindows attribute
829 of QWebSettings to true in order for it to get called.
831 \sa QWebPage::createWindow(), QWebPage::acceptNavigationRequest()
833 QWebView *QWebView::createWindow(QWebPage::WebWindowType type)
841 void QWebView::mouseMoveEvent(QMouseEvent* ev)
844 const bool accepted = ev->isAccepted();
846 ev->setAccepted(accepted);
852 void QWebView::mousePressEvent(QMouseEvent* ev)
855 const bool accepted = ev->isAccepted();
857 ev->setAccepted(accepted);
863 void QWebView::mouseDoubleClickEvent(QMouseEvent* ev)
866 const bool accepted = ev->isAccepted();
868 ev->setAccepted(accepted);
874 void QWebView::mouseReleaseEvent(QMouseEvent* ev)
877 const bool accepted = ev->isAccepted();
879 ev->setAccepted(accepted);
883 #ifndef QT_NO_CONTEXTMENU
886 void QWebView::contextMenuEvent(QContextMenuEvent* ev)
889 const bool accepted = ev->isAccepted();
891 ev->setAccepted(accepted);
894 #endif // QT_NO_CONTEXTMENU
896 #ifndef QT_NO_WHEELEVENT
899 void QWebView::wheelEvent(QWheelEvent* ev)
902 const bool accepted = ev->isAccepted();
904 ev->setAccepted(accepted);
907 #endif // QT_NO_WHEELEVENT
911 void QWebView::keyPressEvent(QKeyEvent* ev)
915 if (!ev->isAccepted())
916 QWidget::keyPressEvent(ev);
921 void QWebView::keyReleaseEvent(QKeyEvent* ev)
925 if (!ev->isAccepted())
926 QWidget::keyReleaseEvent(ev);
931 void QWebView::focusInEvent(QFocusEvent* ev)
936 QWidget::focusInEvent(ev);
941 void QWebView::focusOutEvent(QFocusEvent* ev)
946 QWidget::focusOutEvent(ev);
951 void QWebView::dragEnterEvent(QDragEnterEvent* ev)
953 #ifndef QT_NO_DRAGANDDROP
961 void QWebView::dragLeaveEvent(QDragLeaveEvent* ev)
963 #ifndef QT_NO_DRAGANDDROP
971 void QWebView::dragMoveEvent(QDragMoveEvent* ev)
973 #ifndef QT_NO_DRAGANDDROP
981 void QWebView::dropEvent(QDropEvent* ev)
983 #ifndef QT_NO_DRAGANDDROP
991 bool QWebView::focusNextPrevChild(bool next)
993 if (d->page && d->page->focusNextPrevChild(next))
995 return QWidget::focusNextPrevChild(next);
1000 QVariant QWebView::inputMethodQuery(Qt::InputMethodQuery property) const
1003 return d->page->inputMethodQuery(property);
1009 void QWebView::inputMethodEvent(QInputMethodEvent *e)
1017 void QWebView::changeEvent(QEvent *e)
1019 if (d->page && e->type() == QEvent::PaletteChange)
1020 d->page->setPalette(palette());
1021 QWidget::changeEvent(e);
1025 \fn void QWebView::titleChanged(const QString &title)
1027 This signal is emitted whenever the \a title of the main frame changes.
1033 \fn void QWebView::urlChanged(const QUrl &url)
1035 This signal is emitted when the \a url of the view changes.
1041 \fn void QWebView::statusBarMessage(const QString& text)
1043 This signal is emitted when the status bar \a text is changed by the page.
1047 \fn void QWebView::iconChanged()
1049 This signal is emitted whenever the icon of the page is loaded or changes.
1051 In order for icons to be loaded, you will need to set an icon database path
1052 using QWebSettings::setIconDatabasePath().
1054 \sa icon(), QWebSettings::setIconDatabasePath()
1058 \fn void QWebView::loadStarted()
1060 This signal is emitted when a new load of the page is started.
1062 \sa loadProgress(), loadFinished()
1066 \fn void QWebView::loadFinished(bool ok)
1068 This signal is emitted when a load of the page is finished.
1069 \a ok will indicate whether the load was successful or any error occurred.
1075 \fn void QWebView::selectionChanged()
1077 This signal is emitted whenever the selection changes.
1083 \fn void QWebView::loadProgress(int progress)
1085 This signal is emitted every time an element in the web page
1086 completes loading and the overall loading progress advances.
1088 This signal tracks the progress of all child frames.
1090 The current value is provided by \a progress and scales from 0 to 100,
1091 which is the default range of QProgressBar.
1093 \sa loadStarted(), loadFinished()
1097 \fn void QWebView::linkClicked(const QUrl &url)
1099 This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy
1100 property is set to delegate the link handling for the specified \a url.
1102 \sa QWebPage::linkDelegationPolicy()
1105 #include "moc_qwebview.cpp"