我本愚钝,在网上搜了一下没找到可以运行的栗子,遂在这记录一下吧。
环境:win10 64位系统 qt 4.8.7 (mingw32) qtcreator(4.5.0)
1. 建立一个 Widgets Application 项目,修改 *.pro 文件 ,增加 QT += core gui webkit
1 # 2 #------------------------------------------------- 3 4 QT += core gui webkit 5 6 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 7 8 TARGET = testweb 9 TEMPLATE = app 10 11 # The following define makes your compiler emit warnings if you use 12 # any feature of Qt which has been marked as deprecated (the exact warnings 13 # depend on your compiler). Please consult the documentation of the 14 # deprecated API in order to know how to port your code away from it. 15 DEFINES += QT_DEPRECATED_WARNINGS 16 17 # You can also make your code fail to compile if you use deprecated APIs. 18 # In order to do so, uncomment the following line. 19 # You can also select to disable deprecated APIs only up to a certain version of Qt. 20 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 21 22 23 SOURCES += 24 main.cpp 25 mytestwindow.cpp 26 27 HEADERS += 28 mytestwindow.h 29 30 FORMS += 31 mytestwindow.ui
在 mytestwindow.h 增加
1 public slots: 2 void loadFinished(); 3 void onCall(QString name);
附 mytestwindow.h 全部文件
1 #ifndef MYTESTWINDOW_H 2 #define MYTESTWINDOW_H 3 4 #include <QMainWindow> 5 6 namespace Ui { 7 class MyTestWindow; 8 } 9 10 class MyTestWindow : public QMainWindow 11 { 12 Q_OBJECT 13 14 public: 15 explicit MyTestWindow(QWidget *parent = 0); 16 ~MyTestWindow(); 17 18 public slots: 19 void loadFinished(); 20 void onCall(QString name); 21 22 private: 23 Ui::MyTestWindow *ui; 24 }; 25 26 #endif // MYTESTWINDOW_H
附 mytestwindow.cpp 全部文件
1 #include "mytestwindow.h" 2 #include "ui_mytestwindow.h" 3 #include <QWebView> 4 #include <QWebFrame> 5 #include <QDebug> 6 7 8 MyTestWindow::MyTestWindow(QWidget *parent) : 9 QMainWindow(parent), 10 ui(new Ui::MyTestWindow) 11 { 12 ui->setupUi(this); 13 14 QWebView *view = new QWebView(this->centralWidget()); 15 view->load(QUrl::fromUserInput(QString("D:\Qt\projects\web\testweb\test.html"))); 16 connect(view, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished())); 17 18 view->page()->mainFrame()->addToJavaScriptWindowObject("mytestwin",this); 19 } 20 21 MyTestWindow::~MyTestWindow() 22 { 23 delete ui; 24 } 25 26 void MyTestWindow::loadFinished() 27 { 28 QVariant f1result = ((QWebView*)sender())->page()->mainFrame()->evaluateJavaScript("f1('test param ha ha ha ~~')"); 29 qDebug() << f1result.toString(); 30 } 31 32 void MyTestWindow::onCall(QString name) 33 { 34 qDebug()<<name; 35 }
附 test.html 文件
1 <head> 2 <script LANGUAGE="JavaScript"> 3 function f1 (s) 4 { 5 alert (s) 6 window.mytestwin.onCall("test on call"); 7 return "f1 result ha ha ha ~~" 8 } 9 </script> 10 </head> 11 <body> 12 test html 13 </body>
运行结果如下:
2018-2-9 ps:
问题1: 加载 https 具有ssl的网站异常。
解决1:需要 mingw32optin 目录下libeay32.dll和ssleay32.dll (qt对应mingw32) 复制 到项目的debug/release 目录以下即可。