QWebFrame addToJavaScriptWindowObject() objects are undefined in Javascript

Kyle picture Kyle · Aug 22, 2011 · Viewed 7.2k times · Source

I have started to dig in to C++ and Qt again, and have been mucking around with the WebKit Javascript/Qt bindings. I've got all the moving parts working, with the exception of my QObject subclass being "undefined" on the Javascript side. Here's the simple test app I'm having trouble with:

My main window implementation:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

// instantiate a webview
QWebView *webview = new QWebView(this);
webview->setGeometry(0, 0, 400, 300);
webview->setUrl(QUrl("file://localhost/Users/kyle/Sites/tests/qt/index.html"));

// instantiate and attach our QObject
hello *h = new hello();

QWebFrame *frame = webview->page()->mainFrame();
frame->addToJavaScriptWindowObject("Hello", h);

// show the window
webview->show();
}

Hello.cpp

...snip...

QString hello::say()
{
    return QString("Kyle");
}

Hello.h

...snip includes...

class hello : public QObject
{
    Q_OBJECT

public:
    hello();
    Q_INVOKABLE QString say();

};

The above-mentioned index.html file does a simple alert(Hello.say()) call, but doing typeof Hello, I get undefined.

I'm a bit rusty with C++, and pretty new to Qt, so I'm sure this is a noob mistake, but I'm stumped.

Answer

alexisdm picture alexisdm · Aug 24, 2011

Objects can't be inserted in the page at any time. You should put that line:

frame->addToJavaScriptWindowObject("Hello", h);

in a slot connected to the javaScriptWindowObjectCleared() signal of the QWebFrame and move some code around, so you can access the frame from that slot.

See also the Form Extractor example included with Qt.