QWebPage Class

The QWebPage class provides an object to view and edit web documents. More...

Header: #include <QWebPage>
qmake: QT += webkitwidgets
Since: Qt 4.4

This class was introduced in Qt 4.4.

Public Types

class ChooseMultipleFilesExtensionOption
class ChooseMultipleFilesExtensionReturn
class ErrorPageExtensionOption
class ErrorPageExtensionReturn
class ExtensionOption
class ExtensionReturn
class ViewportAttributes
enum ErrorDomain { QtNetwork, Http, WebKit }
enum Extension { ChooseMultipleFilesExtension, ErrorPageExtension }
enum Feature { Notifications, Geolocation }
enum FindFlag { FindBackward, FindCaseSensitively, FindWrapsAroundDocument, HighlightAllOccurrences, FindAtWordBeginningsOnly, …, FindBeginsInSelection }
flags FindFlags
enum LinkDelegationPolicy { DontDelegateLinks, DelegateExternalLinks, DelegateAllLinks }
enum NavigationType { NavigationTypeLinkClicked, NavigationTypeFormSubmitted, NavigationTypeBackOrForward, NavigationTypeReload, NavigationTypeFormResubmitted, NavigationTypeOther }
enum PermissionPolicy { PermissionUnknown, PermissionGrantedByUser, PermissionDeniedByUser }
enum VisibilityState { VisibilityStateVisible, VisibilityStateHidden, VisibilityStatePrerender, VisibilityStateUnloaded }
enum WebAction { NoWebAction, OpenLink, OpenLinkInNewWindow, OpenLinkInThisWindow, OpenFrameInNewWindow, …, ToggleVideoFullscreen }
enum WebWindowType { WebBrowserWindow, WebModalDialog }

Properties

Public Functions

QWebPage(QObject *parent = Q_NULLPTR)
virtual ~QWebPage()
QAction *action(WebAction action) const
quint64 bytesReceived() const
QMenu *createStandardContextMenu()
QWebFrame *currentFrame() const
virtual bool extension(Extension extension, const ExtensionOption *option = Q_NULLPTR, ExtensionReturn *output = Q_NULLPTR)
bool findText(const QString &subString, FindFlags options = FindFlags())
bool focusNextPrevChild(bool next)
bool forwardUnsupportedContent() const
QWebFrame *frameAt(const QPoint &pos) const
bool hasSelection() const
QWebHistory *history() const
QVariant inputMethodQuery(Qt::InputMethodQuery property) const
bool isContentEditable() const
bool isModified() const
LinkDelegationPolicy linkDelegationPolicy() const
QWebFrame *mainFrame() const
QNetworkAccessManager *networkAccessManager() const
QPalette palette() const
QWebPluginFactory *pluginFactory() const
QSize preferredContentsSize() const
QString selectedHtml() const
QString selectedText() const
void setContentEditable(bool editable)
void setForwardUnsupportedContent(bool forward)
void setLinkDelegationPolicy(LinkDelegationPolicy policy)
void setNetworkAccessManager(QNetworkAccessManager *manager)
void setPalette(const QPalette &palette)
void setPluginFactory(QWebPluginFactory *factory)
void setPreferredContentsSize(const QSize &size) const
void setView(QWidget *view)
void setViewportSize(const QSize &size) const
void setVisibilityState(VisibilityState)
QWebSettings *settings() const
QStringList supportedContentTypes() const
bool supportsContentType(const QString &mimeType) const
virtual bool supportsExtension(Extension extension) const
bool swallowContextMenuEvent(QContextMenuEvent *event)
quint64 totalBytes() const
virtual void triggerAction(WebAction action, bool checked = false)
QUndoStack *undoStack() const
void updatePositionDependentActions(const QPoint &pos)
QWidget *view() const
ViewportAttributes viewportAttributesForSize(const QSize &availableSize) const
QSize viewportSize() const
VisibilityState visibilityState() const

Reimplemented Public Functions

virtual bool event(QEvent *ev) override

Protected Functions

virtual QString chooseFile(QWebFrame *parentFrame, const QString &suggestedFile)
virtual QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues)
virtual QWebPage *createWindow(WebWindowType type)
virtual void javaScriptAlert(QWebFrame *frame, const QString &msg)
virtual bool javaScriptConfirm(QWebFrame *frame, const QString &msg)
virtual void javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID)
virtual bool javaScriptPrompt(QWebFrame *frame, const QString &msg, const QString &defaultValue, QString *result)
virtual QString userAgentForUrl(const QUrl &url) const

Detailed Description

QWebPage holds a main frame responsible for web content, settings, the history of navigated links and actions. This class can be used, together with QWebFrame, to provide functionality like QWebView in a widget-less environment.

QWebPage's API is very similar to QWebView, as you are still provided with common functions like action() (known as pageAction() in QWebView), triggerAction(), findText() and settings(). More QWebView-like functions can be found in the main frame of QWebPage, obtained via the mainFrame() function. For example, the load(), setUrl() and setHtml() functions for QWebPage can be accessed using QWebFrame.

The loadStarted() signal is emitted when the page begins to load.The loadProgress() signal, on the other hand, is emitted whenever an element of the web page completes loading, such as an embedded image, a script, etc. Finally, the loadFinished() signal is emitted when the page contents are loaded completely, independent of script execution or page rendering. Its argument, either true or false, indicates whether or not the load operation succeeded.

Using QWebPage in a Widget-less Environment

Before you begin painting a QWebPage object, you need to set the size of the viewport by calling setViewportSize(). Then, you invoke the main frame's render function (QWebFrame::render()). An example of this is shown in the code snippet below.

Suppose we have a Thumbnail class as follows:

 class Thumbnailer : public QObject
 {
     Q_OBJECT

 public:
     Thumbnailer(const QUrl &url);

 Q_SIGNALS:
     void finished();

 private Q_SLOTS:
     void render();

 private:
     QWebPage page;

 };

The Thumbnail's constructor takes in a url. We connect our QWebPage object's loadFinished() signal to our private slot, render().

 Thumbnailer::Thumbnailer(const QUrl &url)
 {
     page.mainFrame()->load(url);
     connect(&page, SIGNAL(loadFinished(bool)),
         this, SLOT(render()));
 }

The render() function shows how we can paint a thumbnail using a QWebPage object.

 void Thumbnailer::render()
 {
     page.setViewportSize(page.mainFrame()->contentsSize());
     QImage image(page.viewportSize(), QImage::Format_ARGB32);
     QPainter painter(&image);

     page.mainFrame()->render(&painter);
     painter.end();

     QImage thumbnail = image.scaled(400, 400);
     thumbnail.save("thumbnail.png");

     emit finished();
 }

We begin by setting the viewportSize and then we instantiate a QImage object, image, with the same size as our viewportSize. This image is then sent as a parameter to painter. Next, we render the contents of the main frame and its subframes into painter. Finally, we save the scaled image.

See also QWebFrame.

Member Type Documentation

enum QWebPage::ErrorDomain

This enum describes the domain of an ErrorPageExtensionOption object (i.e. the layer in which the error occurred).

ConstantValueDescription
QWebPage::QtNetwork0The error occurred in the QtNetwork layer; the error code is of type QNetworkReply::NetworkError.
QWebPage::Http1The error occurred in the HTTP layer; the error code is a HTTP status code (see QNetworkRequest::HttpStatusCodeAttribute).
QWebPage::WebKit2The error is an internal WebKit error.

This enum was introduced or modified in Qt 4.6.

enum QWebPage::Extension

This enum describes the types of extensions that the page can support. Before using these extensions, you should verify that the extension is supported by calling supportsExtension().

ConstantValueDescription
QWebPage::ChooseMultipleFilesExtension0Whether the web page supports multiple file selection. This extension is invoked when the web content requests one or more file names, for example as a result of the user clicking on a "file upload" button in a HTML form where multiple file selection is allowed.
QWebPage::ErrorPageExtension1Whether the web page can provide an error page when loading fails. (introduced in Qt 4.6)

See also ChooseMultipleFilesExtensionOption, ChooseMultipleFilesExtensionReturn, ErrorPageExtensionOption, and ErrorPageExtensionReturn.

enum QWebPage::Feature

This enum describes the platform feature access categories that the user may be asked to grant or deny access to.

ConstantValueDescription
QWebPage::Notifications0Access to notifications
QWebPage::Geolocation1Access to location hardware or service

See also featurePermissionRequested(), featurePermissionRequestCanceled(), setFeaturePermission(), and PermissionPolicy.

enum QWebPage::FindFlag
flags QWebPage::FindFlags

This enum describes the options available to the findText() function. The options can be OR-ed together from the following list:

ConstantValueDescription
QWebPage::FindBackward1Searches backwards instead of forwards.
QWebPage::FindCaseSensitively2By default findText() works case insensitive. Specifying this option changes the behaviour to a case sensitive find operation.
QWebPage::FindWrapsAroundDocument4Makes findText() restart from the beginning of the document if the end was reached and the text was not found.
QWebPage::HighlightAllOccurrences8Highlights all existing occurrences of a specific string. (This value was introduced in 4.6.)
QWebPage::FindAtWordBeginningsOnly16Searches for the sub-string only at the beginnings of words. (This value was introduced in 5.2.)
QWebPage::TreatMedialCapitalAsWordBeginning32Treats a capital letter occurring anywhere in the middle of a word as the beginning of a new word. (This value was introduced in 5.2.)
QWebPage::FindBeginsInSelection64Begin searching inside the text selection first. (This value was introduced in 5.2.)

The FindFlags type is a typedef for QFlags<FindFlag>. It stores an OR combination of FindFlag values.

enum QWebPage::LinkDelegationPolicy

This enum defines the delegation policies a webpage can have when activating links and emitting the linkClicked() signal.

ConstantValueDescription
QWebPage::DontDelegateLinks0No links are delegated. Instead, QWebPage tries to handle them all.
QWebPage::DelegateExternalLinks1When activating links that point to documents not stored on the local filesystem or an equivalent - such as the Qt resource system - then linkClicked() is emitted.
QWebPage::DelegateAllLinks2Whenever a link is activated the linkClicked() signal is emitted.

See also QWebPage::linkDelegationPolicy.

This enum describes the types of navigation available when browsing through hyperlinked documents.

ConstantValueDescription
QWebPage::NavigationTypeLinkClicked0The user clicked on a link or pressed return on a focused link.
QWebPage::NavigationTypeFormSubmitted1The user activated a submit button for an HTML form.
QWebPage::NavigationTypeBackOrForward2Navigation to a previously shown document in the back or forward history is requested.
QWebPage::NavigationTypeReload3The user activated the reload action.
QWebPage::NavigationTypeFormResubmitted4An HTML form was submitted a second time.
QWebPage::NavigationTypeOther5A navigation to another document using a method not listed above.

See also acceptNavigationRequest().

enum QWebPage::PermissionPolicy

This enum describes the permission policies that the user may set for data or device access.

ConstantValueDescription
QWebPage::PermissionUnknown0It is unknown whether the user grants or denies permission.
QWebPage::PermissionGrantedByUser1The user has granted permission.
QWebPage::PermissionDeniedByUser2The user has denied permission.

See also featurePermissionRequested(), featurePermissionRequestCanceled(), setFeaturePermission(), and Feature.

enum QWebPage::VisibilityState

This enum defines visibility states that a webpage can take.

ConstantValueDescription
QWebPage::VisibilityStateVisible0The webpage is at least partially visible at on at least one screen.
QWebPage::VisibilityStateHidden1The webpage is not visible at all on any screen.
QWebPage::VisibilityStatePrerender2The webpage is loaded off-screen and is not visible.
QWebPage::VisibilityStateUnloaded3The webpage is unloading its content. More information about this values can be found at W3C Recommendation: Page Visibility: visibilityState attribute.

See also QWebPage::visibilityState.

enum QWebPage::WebAction

This enum describes the types of action which can be performed on the web page.

Actions only have an effect when they are applicable. The availability of actions can be be determined by checking isEnabled() on the action returned by action().

One method of enabling the text editing, cursor movement, and text selection actions is by setting contentEditable to true.

ConstantValueDescription
QWebPage::NoWebAction- 1No action is triggered.
QWebPage::OpenLink0Open the current link.
QWebPage::OpenLinkInNewWindow1Open the current link in a new window.
QWebPage::OpenLinkInThisWindow69Open the current link without opening a new window. Used on links that would default to opening in another frame or a new window. (Added in Qt 5.0)
QWebPage::OpenFrameInNewWindow2Replicate the current frame in a new window.
QWebPage::DownloadLinkToDisk3Download the current link to the disk.
QWebPage::CopyLinkToClipboard4Copy the current link to the clipboard.
QWebPage::OpenImageInNewWindow5Open the highlighted image in a new window.
QWebPage::DownloadImageToDisk6Download the highlighted image to the disk.
QWebPage::CopyImageToClipboard7Copy the highlighted image to the clipboard. (Added in Qt 4.8)
QWebPage::CopyImageUrlToClipboard68Copy the highlighted image's URL to the clipboard.
QWebPage::Back8Navigate back in the history of navigated links.
QWebPage::Forward9Navigate forward in the history of navigated links.
QWebPage::Stop10Stop loading the current page.
QWebPage::StopScheduledPageRefresh67Stop all pending page refresh/redirect requests. (Added in Qt 4.7)
QWebPage::Reload11Reload the current page.
QWebPage::ReloadAndBypassCache53Reload the current page, but do not use any local cache. (Added in Qt 4.6)
QWebPage::Cut12Cut the content currently selected into the clipboard.
QWebPage::Copy13Copy the content currently selected into the clipboard.
QWebPage::Paste14Paste content from the clipboard.
QWebPage::Undo15Undo the last editing action.
QWebPage::Redo16Redo the last editing action.
QWebPage::MoveToNextChar17Move the cursor to the next character.
QWebPage::MoveToPreviousChar18Move the cursor to the previous character.
QWebPage::MoveToNextWord19Move the cursor to the next word.
QWebPage::MoveToPreviousWord20Move the cursor to the previous word.
QWebPage::MoveToNextLine21Move the cursor to the next line.
QWebPage::MoveToPreviousLine22Move the cursor to the previous line.
QWebPage::MoveToStartOfLine23Move the cursor to the start of the line.
QWebPage::MoveToEndOfLine24Move the cursor to the end of the line.
QWebPage::MoveToStartOfBlock25Move the cursor to the start of the block.
QWebPage::MoveToEndOfBlock26Move the cursor to the end of the block.
QWebPage::MoveToStartOfDocument27Move the cursor to the start of the document.
QWebPage::MoveToEndOfDocument28Move the cursor to the end of the document.
QWebPage::SelectNextChar29Select to the next character.
QWebPage::SelectPreviousChar30Select to the previous character.
QWebPage::SelectNextWord31Select to the next word.
QWebPage::SelectPreviousWord32Select to the previous word.
QWebPage::SelectNextLine33Select to the next line.
QWebPage::SelectPreviousLine34Select to the previous line.
QWebPage::SelectStartOfLine35Select to the start of the line.
QWebPage::SelectEndOfLine36Select to the end of the line.
QWebPage::SelectStartOfBlock37Select to the start of the block.
QWebPage::SelectEndOfBlock38Select to the end of the block.
QWebPage::SelectStartOfDocument39Select to the start of the document.
QWebPage::SelectEndOfDocument40Select to the end of the document.
QWebPage::DeleteStartOfWord41Delete to the start of the word.
QWebPage::DeleteEndOfWord42Delete to the end of the word.
QWebPage::SetTextDirectionDefault43Set the text direction to the default direction.
QWebPage::SetTextDirectionLeftToRight44Set the text direction to left-to-right.
QWebPage::SetTextDirectionRightToLeft45Set the text direction to right-to-left.
QWebPage::ToggleBold46Toggle the formatting between bold and normal weight.
QWebPage::ToggleItalic47Toggle the formatting between italic and normal style.
QWebPage::ToggleUnderline48Toggle underlining.
QWebPage::InspectElement49Show the Web Inspector with the currently highlighted HTML element.
QWebPage::InsertParagraphSeparator50Insert a new paragraph.
QWebPage::InsertLineSeparator51Insert a new line.
QWebPage::SelectAll52Selects all content.
QWebPage::PasteAndMatchStyle54Paste content from the clipboard with current style. (Added in Qt 4.6)
QWebPage::RemoveFormat55Removes formatting and style. (Added in Qt 4.6)
QWebPage::ToggleStrikethrough56Toggle the formatting between strikethrough and normal style. (Added in Qt 4.6)
QWebPage::ToggleSubscript57Toggle the formatting between subscript and baseline. (Added in Qt 4.6)
QWebPage::ToggleSuperscript58Toggle the formatting between supercript and baseline. (Added in Qt 4.6)
QWebPage::InsertUnorderedList59Toggles the selection between an ordered list and a normal block. (Added in Qt 4.6)
QWebPage::InsertOrderedList60Toggles the selection between an ordered list and a normal block. (Added in Qt 4.6)
QWebPage::Indent61Increases the indentation of the currently selected format block by one increment. (Added in Qt 4.6)
QWebPage::Outdent62Decreases the indentation of the currently selected format block by one increment. (Added in Qt 4.6)
QWebPage::AlignCenter63Applies center alignment to content. (Added in Qt 4.6)
QWebPage::AlignJustified64Applies full justification to content. (Added in Qt 4.6)
QWebPage::AlignLeft65Applies left justification to content. (Added in Qt 4.6)
QWebPage::AlignRight66Applies right justification to content. (Added in Qt 4.6)
QWebPage::DownloadMediaToDisk70Download the hovered audio or video to the disk. (Added in Qt 5.2)
QWebPage::CopyMediaUrlToClipboard71Copy the hovered audio or video's URL to the clipboard. (Added in Qt 5.2)
QWebPage::ToggleMediaControls72Toggles between showing and hiding the controls for the hovered audio or video element. (Added in Qt 5.2)
QWebPage::ToggleMediaLoop73Toggles whether the hovered audio or video should loop on completetion or not. (Added in Qt 5.2)
QWebPage::ToggleMediaPlayPause74Toggles the play/pause state of the hovered audio or video element. (Added in Qt 5.2)
QWebPage::ToggleMediaMute75Mutes or unmutes the hovered audio or video element. (Added in Qt 5.2)
QWebPage::ToggleVideoFullscreen76Switches the hovered video element into or out of fullscreen mode. (Added in Qt 5.2)

enum QWebPage::WebWindowType

This enum describes the types of window that can be created by the createWindow() function.

ConstantValueDescription
QWebPage::WebBrowserWindow0The window is a regular web browser window.
QWebPage::WebModalDialog1The window acts as modal dialog.

Property Documentation

contentEditable : bool

This property holds whether the content in this QWebPage is editable or not

If this property is enabled the contents of the page can be edited by the user through a visible cursor. If disabled (the default) only HTML elements in the web page with their contenteditable attribute set are editable.

This property was introduced in Qt 4.5.

Access functions:

bool isContentEditable() const
void setContentEditable(bool editable)

See also modified, contentsChanged(), and WebAction.

forwardUnsupportedContent : bool

This property holds whether QWebPage should forward unsupported content

If enabled, the unsupportedContent() signal is emitted with a network reply that can be used to read the content.

If disabled, the download of such content is aborted immediately.

By default unsupported content is not forwarded.

Access functions:

bool forwardUnsupportedContent() const
void setForwardUnsupportedContent(bool forward)

hasSelection : const bool

This property holds whether this page contains selected content or not.

Access functions:

bool hasSelection() const

See also selectionChanged().

linkDelegationPolicy : LinkDelegationPolicy

how QWebPage should delegate the handling of links through the linkClicked() signal

The default is to delegate no links.

Access functions:

LinkDelegationPolicy linkDelegationPolicy() const
void setLinkDelegationPolicy(LinkDelegationPolicy policy)

modified : const bool

This property holds whether the page contains unsubmitted form data, or the contents have been changed.

By default, this property is false.

Access functions:

bool isModified() const

See also contentsChanged(), contentEditable, and undoStack().

palette : QPalette

This property holds the page's palette

The base brush of the palette is used to draw the background of the main frame.

By default, this property contains the application's default palette.

Access functions:

QPalette palette() const
void setPalette(const QPalette &palette)

preferredContentsSize : QSize

This property holds a custom size used for laying out the page contents.

By default all pages are laid out using the viewport of the page as the base.

As pages mostly are designed for desktop usage, they often do not layout properly on small devices as the contents require a certain view width. For this reason it is common to use a different layout size and then scale the contents to fit within the actual view.

If this property is set to a valid size, this size is used for all layout needs instead of the size of the viewport.

Setting an invalid size, makes the page fall back to using the viewport size for layout.

This property was introduced in Qt 4.6.

Access functions:

QSize preferredContentsSize() const
void setPreferredContentsSize(const QSize &size) const

See also viewportSize.

selectedHtml : const QString

This property holds the HTML currently selected

By default, this property contains an empty string.

This property was introduced in Qt 4.8.

Access functions:

QString selectedHtml() const

See also selectionChanged() and selectedText().

selectedText : const QString

This property holds the text currently selected

By default, this property contains an empty string.

Access functions:

QString selectedText() const

See also selectionChanged() and selectedHtml().

viewportSize : QSize

This property holds the size of the viewport

The size affects for example the visibility of scrollbars if the document is larger than the viewport.

By default, for a newly-created Web page, this property contains a size with zero width and height.

Access functions:

QSize viewportSize() const
void setViewportSize(const QSize &size) const

See also QWebFrame::render() and preferredContentsSize.

visibilityState : VisibilityState

This property holds the page's visibility state

This property should be changed by Qt applications who want to notify the JavaScript application that the visibility state has changed (e.g. by reimplementing QWidget::setVisible). The visibility state will be updated with the state parameter value only if it's different from the previous set. Then, HTML DOM Document Object attributes 'hidden' and 'visibilityState' will be updated to the correct value and a 'visiblitychange' event will be fired. More information about this HTML5 API can be found at W3C Recommendation: Page Visibility.

By default, this property is set to VisibilityStateVisible.

Access functions:

VisibilityState visibilityState() const
void setVisibilityState(VisibilityState)

Member Function Documentation

QWebPage::QWebPage(QObject *parent = Q_NULLPTR)

Constructs an empty QWebPage with parent parent.

[virtual] QWebPage::~QWebPage()

Destroys the web page.

QAction *QWebPage::action(WebAction action) const

Returns a QAction for the specified WebAction action.

The action is owned by the QWebPage but you can customize the look by changing its properties.

QWebPage also takes care of implementing the action, so that upon triggering the corresponding action is performed on the page.

See also triggerAction().

quint64 QWebPage::bytesReceived() const

Returns the number of bytes that were received from the network to render the current page.

See also totalBytes() and loadProgress().

[virtual protected] QString QWebPage::chooseFile(QWebFrame *parentFrame, const QString &suggestedFile)

This function is called when the web content requests a file name, for example as a result of the user clicking on a "file upload" button in a HTML form.

A suggested filename may be provided in suggestedFile. The frame originating the request is provided as parentFrame.

See also ChooseMultipleFilesExtension.

[virtual protected] QObject *QWebPage::createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues)

This function is called whenever WebKit encounters a HTML object element with type "application/x-qt-plugin". It is called regardless of the value of QWebSettings::PluginsEnabled. The classid, url, paramNames and paramValues correspond to the HTML object element attributes and child elements to configure the embeddable object.

QMenu *QWebPage::createStandardContextMenu()

This function creates the standard context menu which is shown when the user clicks on the web page with the right mouse button. It is called from the default contextMenuEvent() handler. The popup menu's ownership is transferred to the caller.

This function was introduced in Qt 4.5.

[virtual protected] QWebPage *QWebPage::createWindow(WebWindowType type)

This function is called whenever WebKit wants to create a new window of the given type, for example when a JavaScript program requests to open a document in a new window.

If the new window can be created, the new window's QWebPage is returned; otherwise a null pointer is returned.

If the view associated with the web page is a QWebView object, then the default implementation forwards the request to QWebView's createWindow() function; otherwise it returns a null pointer.

If type is WebModalDialog, the application must call setWindowModality(Qt::ApplicationModal) on the new window.

Note: In the cases when the window creation is being triggered by JavaScript, apart from reimplementing this method application must also set the JavaScriptCanOpenWindows attribute of QWebSettings to true in order for it to get called.

See also acceptNavigationRequest() and QWebView::createWindow().

QWebFrame *QWebPage::currentFrame() const

Returns the frame currently active.

See also mainFrame() and frameCreated().

[override virtual] bool QWebPage::event(QEvent *ev)

[virtual] bool QWebPage::extension(Extension extension, const ExtensionOption *option = Q_NULLPTR, ExtensionReturn *output = Q_NULLPTR)

This virtual function can be reimplemented in a QWebPage subclass to provide support for extensions. The option argument is provided as input to the extension; the output results can be stored in output.

The behavior of this function is determined by extension. The option and output values are typically casted to the corresponding types (for example, ChooseMultipleFilesExtensionOption and ChooseMultipleFilesExtensionReturn for ChooseMultipleFilesExtension).

You can call supportsExtension() to check if an extension is supported by the page.

Returns true if the extension was called successfully; otherwise returns false.

See also supportsExtension() and Extension.

bool QWebPage::findText(const QString &subString, FindFlags options = FindFlags())

Finds the specified string, subString, in the page, using the given options.

If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences that exist in the page. All subsequent calls will extend the highlight, rather than replace it, with occurrences of the new string.

If the HighlightAllOccurrences flag is not passed, the function will select an occurrence and all subsequent calls will replace the current occurrence with the next one.

To clear the selection, just pass an empty string.

Returns true if subString was found; otherwise returns false.

bool QWebPage::focusNextPrevChild(bool next)

Similar to QWidget::focusNextPrevChild() it focuses the next focusable web element if next is true; otherwise the previous element is focused.

Returns true if it can find a new focusable element, or false if it can't.

QWebFrame *QWebPage::frameAt(const QPoint &pos) const

Returns the frame at the given point pos, or 0 if there is no frame at that position.

This function was introduced in Qt 4.6.

See also mainFrame() and currentFrame().

QWebHistory *QWebPage::history() const

Returns a pointer to the view's history of navigated web pages.

QVariant QWebPage::inputMethodQuery(Qt::InputMethodQuery property) const

This method is used by the input method to query a set of properties of the page to be able to support complex input method operations as support for surrounding text and reconversions.

property specifies which property is queried.

See also QWidget::inputMethodEvent() and QInputMethodEvent.

[virtual protected] void QWebPage::javaScriptAlert(QWebFrame *frame, const QString &msg)

This function is called whenever a JavaScript program running inside frame calls the alert() function with the message msg.

The default implementation shows the message, msg, with QMessageBox::information.

[virtual protected] bool QWebPage::javaScriptConfirm(QWebFrame *frame, const QString &msg)

This function is called whenever a JavaScript program running inside frame calls the confirm() function with the message, msg. Returns true if the user confirms the message; otherwise returns false.

The default implementation executes the query using QMessageBox::information with QMessageBox::Ok and QMessageBox::Cancel buttons.

[virtual protected] void QWebPage::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID)

This function is called whenever a JavaScript program tries to print a message to the web browser's console.

For example in case of evaluation errors the source URL may be provided in sourceID as well as the lineNumber.

The default implementation prints nothing.

[virtual protected] bool QWebPage::javaScriptPrompt(QWebFrame *frame, const QString &msg, const QString &defaultValue, QString *result)

This function is called whenever a JavaScript program running inside frame tries to prompt the user for input. The program may provide an optional message, msg, as well as a default value for the input in defaultValue.

If the prompt was cancelled by the user the implementation should return false; otherwise the result should be written to result and true should be returned. If the prompt was not cancelled by the user, the implementation should return true and the result string must not be null.

The default implementation uses QInputDialog::getText().

QWebFrame *QWebPage::mainFrame() const

Returns the main frame of the page.

The main frame provides access to the hierarchy of sub-frames and is also needed if you want to explicitly render a web page into a given painter.

See also currentFrame().

QNetworkAccessManager *QWebPage::networkAccessManager() const

Returns the QNetworkAccessManager that is responsible for serving network requests for this QWebPage.

See also setNetworkAccessManager().

QWebPluginFactory *QWebPage::pluginFactory() const

Returns the QWebPluginFactory that is responsible for creating plugins embedded into this QWebPage. If no plugin factory is installed a null pointer is returned.

See also setPluginFactory().

void QWebPage::setNetworkAccessManager(QNetworkAccessManager *manager)

Sets the QNetworkAccessManager manager responsible for serving network requests for this QWebPage.

Note: It is currently not supported to change the network access manager after the QWebPage has used it. The results of doing this are undefined.

See also networkAccessManager().

void QWebPage::setPluginFactory(QWebPluginFactory *factory)

Sets the QWebPluginFactory factory responsible for creating plugins embedded into this QWebPage.

Note: The plugin factory is only used if the QWebSettings::PluginsEnabled attribute is enabled.

See also pluginFactory().

void QWebPage::setView(QWidget *view)

Sets the view that is associated with the web page.

See also view().

QWebSettings *QWebPage::settings() const

Returns a pointer to the page's settings object.

See also QWebSettings::globalSettings().

QStringList QWebPage::supportedContentTypes() const

Returns the list of all content types supported by QWebPage.

bool QWebPage::supportsContentType(const QString &mimeType) const

Returns true if QWebPage can handle the given mimeType; otherwise, returns false.

[virtual] bool QWebPage::supportsExtension(Extension extension) const

This virtual function returns true if the web page supports extension; otherwise false is returned.

See also extension().

bool QWebPage::swallowContextMenuEvent(QContextMenuEvent *event)

Filters the context menu event, event, through handlers for scrollbars and custom event handlers in the web page. Returns true if the event was handled; otherwise false.

A web page may swallow a context menu event through a custom event handler, allowing for context menus to be implemented in HTML/JavaScript. This is used by Google Maps, for example.

quint64 QWebPage::totalBytes() const

Returns the total number of bytes that were received from the network to render the current page, including extra content such as embedded images.

See also bytesReceived().

[virtual] void QWebPage::triggerAction(WebAction action, bool checked = false)

This function can be called to trigger the specified action. It is also called by Qt WebKit if the user triggers the action, for example through a context menu item.

If action is a checkable action then checked specified whether the action is toggled or not.

See also action().

QUndoStack *QWebPage::undoStack() const

Returns a pointer to the undo stack used for editable content.

See also modified.

void QWebPage::updatePositionDependentActions(const QPoint &pos)

Updates the page's actions depending on the position pos. For example if pos is over an image element the CopyImageToClipboard action is enabled.

[virtual protected] QString QWebPage::userAgentForUrl(const QUrl &url) const

This function is called when a user agent for HTTP requests is needed. You can reimplement this function to dynamically return different user agents for different URLs, based on the url parameter.

The default implementation returns the following value:

"Mozilla/5.0 (%Platform%%Security%%Subplatform%) AppleWebKit/%WebKitVersion% (KHTML, like Gecko) %AppVersion Safari/%WebKitVersion%"

In this string the following values are replaced at run-time:

  • %Platform% expands to the windowing system followed by "; " if it is not Windows (e.g. "X11; ").
  • %Security% expands to "N; " if SSL is disabled.
  • %Subplatform% expands to the operating system version (e.g. "Windows NT 6.1" or "Intel Mac OS X 10.5").
  • %WebKitVersion% is the version of WebKit the application was compiled against.
  • %AppVersion% expands to QCoreApplication::applicationName()/QCoreApplication::applicationVersion() if they're set; otherwise defaulting to Qt and the current Qt version.

QWidget *QWebPage::view() const

Returns the view widget that is associated with the web page.

See also setView().

ViewportAttributes QWebPage::viewportAttributesForSize(const QSize &availableSize) const

Computes the optimal viewport configuration given the availableSize, when user interface components are disregarded.

The configuration is also dependent on the device screen size which is obtained automatically. For testing purposes the size can be overridden by setting two environment variables QTWEBKIT_DEVICE_WIDTH and QTWEBKIT_DEVICE_HEIGHT, which both needs to be set.

The ViewportAttributes includes a pixel density ratio, which will also be exposed to the web author though the -webkit-pixel-ratio media feature. This is the ratio between 1 density-independent pixel (DPI) and physical pixels.

A density-independent pixel is equivalent to one physical pixel on a 160 DPI screen, so on our platform assumes that as the baseline density.

The conversion of DIP units to screen pixels is quite simple:

pixels = DIPs * (density / 160).

Thus, on a 240 DPI screen, 1 DIPs would equal 1.5 physical pixels.

An invalid instance will be returned in the case an empty size is passed to the method.

Note: The density is automatically obtained from the DPI of the screen where the page is being shown, but as many X11 servers are reporting wrong DPI, it is possible to override it using QX11Info::setAppDpiY().