1,把QT对象加入到JS中,并实现JS调用QT对象。
// 实现一个新类
class QFoo : public QObject
{
Q_OBJECT
public:
QFoo(QObject *parent) {}
void initialize(QWebView *wv);
public slots:
void print(const QString &msg);
private slots:
void addObject();
private:
QWebFrame *wf;
};
void QFoo::initialize(QWebView *wv)
{
wf = wv->page()->mainFrame();
// Add to the javascript window object
addObject();
// connect the signal for javascript window object cleared, which happened
// at page switching etc.
connect(wf, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addObject()));
}
void QFoo::addObject()
{
wf->addToJavaScriptWindowObject(QString("QFoo"), this);
}
void QFoo::print(const QString &msg)
{
qDebug() << "Output the message " << msg;
}
int main(int argc, char *argv[])
{
QApplication test(argc, argv);
QWebView *wv = new QWebView();
QFoo *foo = new QFoo(wv);
foo->initialize(wv);
wv->setUrl(QUrl("foo.html"));
wv->show();
return test.exec();
}
//定义QT对象
class WebApp : public QObject
{
Q_OBJECT
public:
WebApp(QObject *parent){}
void initialize(QWebView *wv);
signals: //定义QT信号
void launchSignal(QString obj);
void getAppListSignal(QString obj);
public slots:
void launch(const QString &appName);
void getAppList();
private slots:
void addObject();
private:
QWebFrame *wf;
};
//QT对象如何发射信号
void WebApp::launch(const QString &appName)
{
QString url = "";
if(appName == "EManual"){
url = "{\"ip\":\"192.168.42.129\",\"port\":\"12100\"}";
}else if(appName == "DBA"){
url = "{\"ip\":\"192.168.42.129\",\"port\":\"12102\"}";
}
/* send signal */
emit launchSignal(url);
}
HTML测试代码
//定义QT对象
class WebApp : public QObject
{
Q_OBJECT
public:
WebApp(QObject *parent){}
void initialize(QWebView *wv);
public slots:
//定义槽函数,其可以返回和接受JS对象
QMap slotThatReturns(const QMap& object);
private slots:
void addObject();
private:
QWebFrame *wf;
//返回的JS对象
QMap m_returnObject;
};
//返回对象
QMap WebApp::slotThatReturns(const QMap& object)
{
qDebug() << "SampleQObject::slotThatReturns";
this->m_returnObject.clear();
this->m_returnObject.unite(object);
QString addedBonus = QString::number(object["intValue"].toInt(),
10).append(" added bonus.");
this->m_returnObject["stringValue"] = QVariant(addedBonus);
qDebug() << "SampleQObject::slotThatReturns" << this->m_returnObject;
return this->m_returnObject; // 返回m_returnObject包含有字符串 1 added bonus
}
//定义QT对象
class WebApp : public QObject
{
Q_OBJECT
public:
WebApp(QObject *parent){}
void initialize(QWebView *wv);
public slots:
//定义槽函数,其可以返回和接受JS对象
void getAsynCallBack(const QString &type,const QString &success,const QString $error);
private slots:
void addObject();
private:
QWebFrame *wf;
};
//函数实现
void Vehicle::getAsynCallBack(const QString &type,const QString &success,const QString $error)
{
QString msg = "";
//此处省略n行
if(error)
{
qDebug() << "error! " << msg;
msg = "{\"status\":\"error\",\"errorid\":\"-1\"}";
wf->evaluateJavaScript("error('" + msg + "')");
}
else
{
qDebug() << "error! " << msg;
msg = "{\"status\":\"ok\"}";
wf->evaluateJavaScript("success('" + msg + "')");
}
}
HTML测试代码