2013-04-23 30 views
2

我有一個小問題,我希望你能幫助我。QT5 Html5ApplicationViewer - C++調用?

第一:我搜索了幾天,發現了一些不同的解決方案,但他們都沒有爲我工作。

我基本上使用HTML5和Javascript構建了一個小應用程序 - 沒有問題。但現在我想將所有的東西保存到一個文件中。這也不是真正的問題,fstreams很容易。

現在,這是我的問題:如何調用我的功能?我已經嘗試了幾種方法,比如製作一個QtObject和類似的東西,但這當然不起作用,因爲我必須將Javascript函數與我的C++函數連接起來。因爲我閱讀了JS-Bridge-Docu(http://qt-project.org/doc/qt-4.8/qtwebkit-bridge.html),但是我沒有很好地理解它(這絕對是在可能性範圍內!),或者它對於我的問題沒有足夠的特定性,因爲我使用內置的Html5ApplicationViewer類而不是QtWeb類之一。

你能否給我解決方案,或者至少有一種方法可以解決這個問題?這真的讓我發瘋,因爲這是我項目中唯一的困難。

目前我的代碼是這樣的:

#include <QApplication> 
#include <fstream> 
#include "html5applicationviewer.h" 

using namespace std; 

void initFile() { 
    fstream f; 
    f.open("music.nxc", ios::trunc|ios::out); 
    f << "task main() {" << endl; 
    f.close(); 
} 

class fileSave : public QObject { 
public: 
    void saveToFile(); 
}; 

void fileSave::saveToFile() { 
    fstream f; 
    f.open("music.nxc", ios::out|ios::app); 
    f << "success!" << endl; 
    f.close(); 
} 

int main(int argc, char *argv[]) { 
    QApplication app(argc, argv); 

    Html5ApplicationViewer viewer; 
    viewer.resize(1280, 800); 
    viewer.setOrientation(Html5ApplicationViewer::ScreenOrientationAuto); 
    viewer.showExpanded(); 

    viewer.loadFile(QLatin1String("html/index.html")); 

    initFile(); 
    fileSave file; 

    return app.exec(); 
} 

我知道代碼是不是真的好,但我會清理之後這個問題得到解決。

+0

你可以注入你的QObject到Web視圖幀。注入對象的所有插槽對於javascript都是可見的。看到我的回答類似的問題:http://stackoverflow.com/questions/14127098/qtwebview-c-how-to-get-javascript-string-returned-from-linkclicked-event – Archie 2013-08-22 19:44:49

回答

0

abc.h

protected slots: 
    void f(); 

abc.cpp

//in constructor 
//make sure that page already loaded 
webView->page()->mainFrame()->addToJavaScriptWindowObject("qt", this); 


// implement function 
void Abc::f() 
{ 
    // do what you want to do 
} 

abc.js

qt.f(); 
+0

什麼是webView在「webView- > page() - > mainFrame() - > addToJavaScriptWindowObject(「qt」,this);「 – Prasoon 2014-02-27 12:25:19

+0

@Prasoon'webView'是'QWebView'的一個實例,它是一個添加到主窗口的窗口小部件。 – 2014-03-01 04:19:46

0

interfaced CodeMirror在Qt的WebView中,這裏是基本的接口

void CodeMirror::loadFinished(bool ok) { 
    emit userMessage(log, QString("loadFinished %1... (len %2, ok %3)").arg(text.left(20)).arg(text.length()).arg(ok)); 
    if (ok) { 
     frame()->addToJavaScriptWindowObject("proxy", this); 
     if (text.length()) 
      run("editor.setValue(proxy.plainText)"); 
     run("editor.on(\"change\", function() { proxy.onChange() })"); 
    } 
} 

在CodeMirror.h,我有

//! serve F1 in editor 
Q_INVOKABLE void helpRequest(QString topic); 

,允許從JavaScript調用的Qt。例如,從CodeMirror.html

extraKeys:{ 「F1」:功能(釐米){ proxy.helpRequest(cm.getTokenAt(cm.getCursor())的字符串。) }}

另反過來想,我有

void CodeMirror::run(QString script) const { 
    frame()->evaluateJavaScript(script); 
} 

,你可以看到,它是從loadFinished叫...