2016-12-05 81 views
2

我有4個qml文件和一個main.cpp來加載qml文件。 是否有可能爲這4個qml文件創建1個dll文件。 並在不同的應用程序中使用它,如果是的話如何做到這一點。如何在QT/QML中創建共享庫

+0

你爲什麼要這樣做?如果它只有qml文件,只需將qml文件複製到其他應用程序。完成。 – MrBlueSky

回答

2

看一看的文檔QML Modules

存在用於QML-只有模塊的選項,C++之用,混合模式。

3

如前所述,不需要僅將qml文件嵌入庫中。但是,當然,你有權做到你想做的一切,即使是那樣。我知道至少有2種方式來做到這一點:

1.創建二進制資源文件
準備含QML文件的資源文件,然後編譯:

rcc -binary plugin.qrc -o plugin.rcc 

現在你可以包含這個文件到您的應用:

QResource::registerResource("plugin.rcc"); 

,並把它作爲常規的QRC文件:

QResource::registerResource(qApp->applicationDirPath() + "/plugin.rcc"); 
QQuickView *view = new QQuickView(); 
view->setSource(QUrl("qrc:/qml/myfile.qml")); 

這裏qml/是資源文件中的前綴。

2.共享庫
另一種方法是創建一個包含相同資源文件的共享庫。例如下面的接口插件的共享庫可實現:

interface.h

#ifndef PLUGIN_INTERFACE_H 
#define PLUGIN_INTERFACE_H 

#include <QString> 
#include <QObject> 

class PluginInterface 
{ 
public: 
    virtual ~PluginInterface() {} 
    virtual QByteArray getQML(const QString &name) = 0; 
}; 

#define PluginInterface_iid "org.qt-project.PluginInterface" 

Q_DECLARE_INTERFACE(PluginInterface, PluginInterface_iid) 

#endif 

及其實施是:

QByteArray PluginImpl::getQML(const QString &name) 
{ 
    QFile file(":/qml/" + name); 
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) 
     return QByteArray(); 
    return file.readAll(); 
} 

現在,在您的應用程序加載插件,並以字符串形式獲取其資源:

QDir pluginsDir(qApp->applicationDirPath()); 
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath("plugin.dll")); 
QObject *plugin = pluginLoader.instance(); 
if (plugin) { 
    PluginInterface *pluginInstance = qobject_cast<PluginInterface *>(plugin); 
    if (pluginInstance) { 
     QByteArray content = pluginInstance->getQML("file1.qml"); 
     QQuickView *view = new QQuickView(); 
     QQmlComponent component(view->engine()); 
     component.setData(content, QUrl()); 
     QQuickItem *childItem = qobject_cast<QQuickItem*>(component.create()); 
     childItem->setParentItem(view->contentItem()); 

     QWidget *container = QWidget::createWindowContainer(view); 
     container->setFocusPolicy(Qt::TabFocus); 
     ui->verticalLayout->addWidget(container); 
    } 
} 

但是請注意,在部署應用程序時,您必須複製所有qml系統文件,如#QTPATH/qml/QtQml,#QTPATH/qml/QtQuick.2,#QTPATH/qml/QtQuick.2等

鏈接:

+0

在Win和MacOS上部署部署工具正確識別的依賴項時,授予使用'qmldir'參數的權限。如果我是你,我的世界已經補充說。順便說一句好的答案。 – BaCaRoZzo