我又开始深入研究 C++ 和 Qt,并且一直在研究 WebKit Javascript/Qt 绑定。我的所有活动部件都在工作,除了我的 QObject 子类在 Javascript 端是“未定义的”。这是我遇到问题的简单测试应用程序:
我的主窗口实现:
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();
}
你好.cpp
...snip...
QString hello::say()
{
return QString("Kyle");
}
你好.h
...snip includes...
class hello : public QObject
{
Q_OBJECT
public:
hello();
Q_INVOKABLE QString say();
};
上面提到的 index.html 文件做了一个简单的alert(Hello.say())
调用,但是这样做typeof Hello
,我得到了 undefined。
我对 C++ 有点生疏,而且对 Qt 很陌生,所以我确信这是一个菜鸟错误,但我很难过。