Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Fancy Browser Example

Files:

The Fancy Browser example shows how to use jQuery with QtWebKit to create a web browser with special effects and content manipulation.

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.

MainWindow Class Definition

The MainWindow class inherits QMainWindow. It implements a number of slots to perform actions on both the application and on the web content.

 class MainWindow : public QMainWindow
 {
     Q_OBJECT

 public:
     MainWindow();

 protected slots:

     void adjustLocation();
     void changeLocation();
     void adjustTitle();
     void setProgress(int p);
     void finishLoading(bool);

     void highlightAllLinks();
     void rotateImages(bool toggle);
     void removeGifImages();
     void removeInlineFrames();
     void removeObjectElements();
     void removeEmbeddedElements();

 private:
     QString jQuery;
     QWebView *view;
     QLineEdit *locationEdit;
     int progress;

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.

MainWindow Class Implementation

We start by implementing the constructor.

 MainWindow::MainWindow()
 {
     progress = 0;

     QFile file;
     file.setFileName(":/jquery.min.js");
     file.open(QIODevice::ReadOnly);
     jQuery = file.readAll();
     file.close();

The first part of the constructor sets the value of 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.

     view = new QWebView(this);
     view->load(QUrl("http://www.google.com/ncr"));
     connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
     connect(view, SIGNAL(titleChanged(const 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);

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.

     QMenu *effectMenu = menuBar()->addMenu(tr("&Effect"));
     effectMenu->addAction("Highlight all links", this, SLOT(highlightAllLinks()));

     QAction *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);
 }

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.

 void MainWindow::adjustLocation()
 {
     locationEdit->setText(view->url().toString());
 }

 void MainWindow::changeLocation()
 {
     QUrl url = QUrl(locationEdit->text());
     view->load(url);
     view->setFocus();
 }

When the page is loaded, adjustLocation() updates the address bar; adjustLocation() is triggered by the loadFinished() signal in QWebView. In 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, adjustLocation() will be run once more to update the address bar.

 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();
 }

adjustTitle() sets the window title and displays the loading progress. This slot is triggered by the titleChanged() signal in QWebView.

 void MainWindow::finishLoading(bool)
 {
     progress = 100;
     adjustTitle();
     view->page()->mainFrame()->evaluateJavaScript(jQuery);
 }

When a web page has loaded, finishLoading() is triggered by the loadFinished() signal in QWebView. finishLoading() then updates the progress in the title bar and calls 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.

 void MainWindow::highlightAllLinks()
 {
     QString code = "$('a').each( function () { $(this).css('background-color', 'yellow') } )";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

The first jQuery-based function, highlightAllLinks(), is designed to highlight all links in the current webpage. The JavaScript code looks for web elements named a, which is the tag for a hyperlink. For each such element, the background color is set to be yellow by using CSS.

 void MainWindow::rotateImages(bool toggle)
 {
     QString code = "$('img').each( function () { $(this).css('-webkit-transition', '-webkit-transform 2s') } )";
     view->page()->mainFrame()->evaluateJavaScript(code);
     if (toggle)
         code = "$('img').each( function () { $(this).css('-webkit-transform', 'rotate(180deg)') } )";
     else
         code = "$('img').each( function () { $(this).css('-webkit-transform', 'rotate(0deg)') } )";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

The rotateImages() function rotates the images on the current web page. Webkit supports CSS transforms and this JavaScript code looks up all img elements and rotates the images 180 degrees and then back again.

 void MainWindow::removeGifImages()
 {
     QString code = "$('[src*=gif]').remove()";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

 void MainWindow::removeInlineFrames()
 {
     QString code = "$('iframe').remove()";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

 void MainWindow::removeObjectElements()
 {
     QString code = "$('object').remove()";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

 void MainWindow::removeEmbeddedElements()
 {
     QString code = "$('embed').remove()";
     view->page()->mainFrame()->evaluateJavaScript(code);
 }

The remaining four methods remove different elements from the current web page. removeGifImages() removes all Gif images on the page by looking up the src attribute of all the elements on the web page. Any element with a gif file as its source is removed. removeInlineFrames() removes all iframe or inline elements. removeObjectElements() removes all object elements, and removeEmbeddedElements() removes any elements such as plugins embedded on the page using the embed tag.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 44
  2. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le blog Digia au hasard

Logo

Déploiement d'applications Qt Commercial sur les tablettes Windows 8

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.5
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web