Qt和网页中的JavaScript函数相互调用的实现

下面的说明来自Qt源代码中的qwebpluginfactory.cpp文件中的介绍说明,引用一下。

/*!

    \class QWebPluginFactory

    \since 4.4

    \brief The QWebPluginFactory class is used to embed custom data types in web pages.


    \inmodule QtWebKit


    The HTML \c{<object>} tag is used to embed arbitrary content into a web page,

    for example:


    \code

    <object type="application/x-pdf" data="http://qt.nokia.com/document.pdf"></object>

    \endcode


    QtWebkit will natively handle the most basic data types like \c{text/html} and

    \c{image/jpeg}, but for any advanced or custom data types you will need to

    provide a handler yourself.


    QWebPluginFactory is a factory for creating plugins for QWebPage, where each

    plugin provides support for one or more data types. A plugin factory can be

    installed on a QWebPage using QWebPage::setPluginFactory().


    \note The plugin factory is only used if plugins are enabled through QWebSettings.


    You provide a QWebPluginFactory by implementing the plugins() and the

    create() methods. For plugins() it is necessary to describe the plugins the

    factory can create, including a description and the supported MIME types.

    The MIME types each plugin can handle should match the ones specified in

    in the HTML \c{<object>} tag of your content.


    The create() method is called if the requested MIME type is supported. The

    implementation has to return a new instance of the plugin requested for the

    given MIME type and the specified URL.


    The plugins themselves are subclasses of QObject, but currently only plugins

    based on either QWidget or QGraphicsWidget are supported.

---------------------------------------------------------------------------------------------

一、 按照上面给出的说明,如果要实现一个可以被网页中的JS调用的Qt方法,需要注意:

1. 需要继承QWebPluginFactory来实现自己的plugin类 2. 重载自定义plugin类的create()和plugins()方法 3. create()要实现创建特定的工JS调用的对象 4. plugins() 需要返回适当的QList<> 5. JS调用的方法的对象需要继承自QWidget或者QGraphicsWidget,而不是QObject


二、给出的实例代码如下:

     定义JS调用方法的对象:

          class IntelliPlugin : public QWebPluginFactory

     实现其对应的create()和plugins()方法:


QObject* IntelliPlugin::create(const QString &mimeType, const QUrl &, const QStringList &argumentNames, const QStringList &argumentValues) const

{qDebug()<<"IntelliPlugin::create()"<<endl;foreach(MimeTypemime,this->m_mimeType){if(!mime.name.isEmpty()&&mime.name==mimeType){if(mimeType=="application/print-plugin"){qDebug()<<"createshineprint"<<endl;ShinePrint*pShinePrint=newShinePrint(); /*ShinePrint就是JS调用方法的类*/qDebug()<<"finishcreateshineprint."<<endl;returnpShinePrint;}}}returnNULL;}


QList<IntelliPlugin::Plugin>IntelliPlugin::plugins()const{Pluginplugin;plugin.name="application/print-plugin";plugin.description="JustforPrintMessagecalltest";plugin.mimeTypes.append(m_mimeType);QList<IntelliPlugin::Plugin>plugList;plugList.append(plugin);returnplugList;}

在main函数中需要执行的代码:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://127.0.0.1/wyyxfj.html