Matthias
Matthias

Reputation: 471

Call a Qt function from Javascript code

I have a Qt project with a Webview which is loading a HTML file which is Javascriptfiles. Now I want to call a function on Qt side via JavaScript.

So, having the following Qt function:

void MainWIndow::myFunction(angle)
{
    qDebug() << angle;
}

I want to call it from JavaScript side:

function angleChanged(angle){
    Qt.MainWIndow::myFunction(angle);
}

How can I do this?

Upvotes: 1

Views: 794

Answers (1)

Reza Ebrahimi
Reza Ebrahimi

Reputation: 3689

If Qt is your JavaScriptWindowObject, you should use:

In your Qt code behind (MainWIndow class):

MainWIndow.h file:

public slots:
    void populateJavaScriptWindowObject();
    void myFunction(int angle);

MainWIndow.cppfile:

//in constructor
connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
         this, SLOT(populateJavaScriptWindowObject()));

//in populateJavaScriptWindowObject SLOT
void MainWindow::populateJavaScriptWindowObject()
{
    QWebFrame *frame = ui->webView->page()->mainFrame();
    frame->addToJavaScriptWindowObject("Qt", this);
}

In your Javascript code:

function angleChanged(angle) {
    Qt.myFunction(angle);
}

Upvotes: 1

Related Questions