知乎写给女儿的:Qt WebKit可以做什么(三)——开发包含丰富web内容的本地应用

来源:百度文库 编辑:偶看新闻 时间:2024/04/29 07:34:59

Qt WebKit可以做什么(三)——开发包含丰富web内容的本地应用

作者: Dawei Cheng 程大伟 (Intel) (16 篇文章) 日期: 六月 9, 2010 在 10:42 上午

这一篇我们来看看如何在Qt WebKit 中使用web开发的工具去开发包含web内容的本地。
注:本系列文章重在分享一下开发过程,至于webkit如何去解释HTML的DOM tree 以及如何去rendering HTML 和JavaScript 可以参考http://webkit.org/。 
在分享开发过程之前,首先还是看一下这个web应用的架构。
1. 开发环境:

    • Based on QtWebKit browser engine
    • Developed with HTML, CSS and JavaScript
    • Used by Qt Creator for Windows
      • other IDEs, such as Visual Studio or Eclipse, as well.

2. 新建项目:

    1. Start the Qt Creator IDE.
    2. Select File > New File or Project... > Projects > Qt4 Gui Application.
    3. Give the project a name and set its location.
    4. Check the QtWebKit module and click Next.
    5. click Finish.

3. 修改代码: 此时在creator左边edit栏目里会看到project的源代码。打开头文件widgetwindow.h,做如下修改:

    1. #ifndef WIDGETWINDOW_H
    2. #define WIDGETWINDOW_H
    3. #include
    4. #include
    5. class QWebView;
    6. class WidgetWindow : public QMainWindow
    7. {
    8. Q_OBJECT
    9. public:
    10. WidgetWindow(QWidget *parent = 0);
    11. ~WidgetWindow();
    12. private:
    13. void setupUI();
    14. //声明用来显示web应用的函数
    15. QWebView* createWebView();
    16. private:
    17. QPointer webView;
    18. };
    19. #endif // WIDGETWINDOW_H

4. 显示web内容

    1. 在Qt project中创建web应用所需要的HTML, CSS和JavaScript文件,且假设其分别在html/, style/, 和 scripe/文件夹里。文件夹视图如下:如果想了解更多关于web开发,请点此进入:http://zh.html.net/tutorials/html/
            • html/ (HTML files)
            • style/ (CSS files)
            • script/ (JavaScript files)
    2. Create the resource file。 Qt中是通过qrc文件来实现对web内容文件的链接的。一下是qrc文件 helloqtwebkit.qrc的内容。
        1. html/index.html
        2. style/general.css
        3. script/basic.js
    3. 打开HTML文件,将HTML文件代码粘贴如下: 这是一个很简单的helloDemo。
        1. /* add ‘qrc:/’ in the front of css/js files address */
        2. Hello Qt WebKit

  • 5. 函数实现。 打开函数文件 widgetwindow.cpp, 实现之前声明的createwebview函数。

          1. /* display the web application by rendering html file */
          2. QWebView* WidgetWindow::createWebView()
          3. {
          4. QWebView* view = new QWebView(this);
          5. /* load the html file location to Qurl */
          6. view->load(QUrl("qrc:/html/index.html"));
          7. return view;
          8. }

    6. 至此,工作全部完成。build the application. 将会出现期待已久的JavaScript的hello按钮。

    这一篇主要讲解了如何使用HTML CSS 和JavaScript在Qt webkit引擎上开发web应用。
    本篇的源代码可以在此下载: 1QtWebHello.zip http://software.intel.com/file/28104
    下一篇我们将了解如何将Qt本地的Object 和JavaScript进行交互。这对web开发非常有用。