如何在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
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等等
链接:
- Resource compiler
- Same theme
- Plugin example
这篇关于如何在QT/QML中创建共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!