有2个应用:
在某处创建一个文件,然后
应该沿着一些路径获取文件的内容。
我能否在第一个应用程序中指定 QSettings 中文件的路径,然后在第二个应用程序中从注册表中获取此路径并通过它找到文件?
请告诉我一个简单的例子。
最佳答案
我不能建议基于注册表的跨平台方法,但想展示另一种方法。
方法一(基于普通ini文件)
- 将路径存储在一些常见的 ini 文件中,例如
<some_common_path>/settings_common.ini
.两个应用程序都应有权访问该文件:
App 1(作家)
#include <QtCore/QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QThread>
const QString CommonSettingsFilePath = "c:/temp/settings_common.ini";
const QString CommonKey = "common/path";
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
for(;;)
{
static int it = 0;
QString pathString = QString("path_%1").arg(it++);
QSettings settings(CommonSettingsFilePath, QSettings::IniFormat);
settings.setValue(CommonKey, pathString);
QThread::sleep(1);
}
return a.exec();
}
应用 2(阅读器)
#include <QtCore/QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QThread>
const QString CommonSettingsFilePath = "c:/temp/settings_common.ini";
const QString CommonKey = "common/path";
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
for (;;)
{
QSettings settings(CommonSettingsFilePath, QSettings::IniFormat);
QString pathString = settings.value(CommonKey, "").toString();
qDebug() << "Path read from ini =" << pathString;
QThread::sleep(2);
}
return a.exec();
}
App 2 的可能输出:
Path read from ini = "path_6"
Path read from ini = "path_8"
Path read from ini = "path_9"
Path read from ini = "path_11"
...
方法二(基于进程间通信)
IPC使用 Qt Remote Objects API :
App1 是 Source , App2(阅读器)将是 Replica ,路径是一个属性。
只显示要点。
在 App1 和 App2 .pro 文件中添加 remoteobjects
模块:
QT += core remoteobjects ...
path.rep 文件:
#include <QtCore>
#include <QString>
class Path
{
PROP(QString path);
};
在 App1 pro 中:
REPC_SOURCE = path.rep
App1 类:
#include "rep_path_source.h"
class CommonPath : public PathSimpleSource
{
Q_OBJECT
};
然后在 App1 中:
CommonPath sourcePath;
QRemoteObjectHost sourceNode(QUrl("local:path")); // create host node
sourceNode.enableRemoting(&sourcePath); // enable remoting/sharing
...
sourcePath.setPath("some_path_aaa");
在 App2 pro 中:
REPC_REPLICA = path.rep
此外在 App2 中:
#include "rep_path_replica.h"
QSharedPointer<PathReplica> replica;
QRemoteObjectNode repNode; // create remote object node
repNode.connectToNode(QUrl("local:path")); // connect with remote host node
replica.reset(repNode.acquire<PathReplica>()); // acquire replica of source from host node
replica->waitForSource();
...
qDebug() << replica->path();
当然,您可以通过这种方式分发所有必要的数据,而不仅仅是路径。
关于c++ - 我可以为 2 个或更多应用程序进行 QSettings 设置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478635/