如何在 QT/QML 中创建共享库 [英] How create shared library in QT/QML
问题描述
我有 4 个 qml 文件和一个 main.cpp 来加载 qml 文件.我是否可以为这 4 个 qml 文件创建 1 个 dll 文件.并在不同的应用程序中使用它,如果可以的话怎么做.
I have 4 qml files and one main.cpp to load qml file. Is it possible for me to create 1 dll file for those 4 qml file. And use it in different application if so how to do that.
推荐答案
如前所述,没有必要只在库中嵌入 qml 文件.但当然,你有权做任何你想做的事,即便如此.我知道至少有两种方法可以做到这一点:
As already said, there is no need for embedding qml files only in a library. But of course you have the right to do all you want, even that. I know at least 2 ways to do that:
1.创建二进制资源文件
准备包含qml文件的资源文件,然后编译:
1. Create binary resource file
Prepare resource file containing qml files and then compile it:
rcc -binary plugin.qrc -o plugin.rcc
现在您可以将此文件包含到您的应用程序中:
Now you can include this file into your application :
QResource::registerResource("plugin.rcc");
并将其用作常规 qrc 文件:
and use it as regular qrc file:
QResource::registerResource(qApp->applicationDirPath() + "/plugin.rcc");
QQuickView *view = new QQuickView();
view->setSource(QUrl("qrc:/qml/myfile.qml"));
这里 qml/
是资源文件中的前缀.
Here qml/
is prefix in resource file.
<强>2.共享库
另一种方法是创建一个包含相同资源文件的共享库.例如您的插件的共享库实现了以下接口:
2. Shared library
Another way is to create a shared library containing the same resource file. For example your plugin's shared library implements following interface:
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();
}
现在,在您的应用程序中加载您的插件并将其资源作为字符串获取:
Now, in your application you load your plugin and get its resource as a string:
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等等
链接:
这篇关于如何在 QT/QML 中创建共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!