我需要知道如何获取用户的用户名和/或主目录。我已经搜索了一段时间,但只能找到 C++ 或 BASH 的变量。
如何获取用户名或主目录?我正在用 QML 写作。
这就是我实现它的方式:
QmlEnvironmentVariable.h
#ifndef QMLENVIRONMENTVARIABLE_H
#define QMLENVIRONMENTVARIABLE_H
#include <QObject>
class QQmlEngine;
class QJSEngine;
class QmlEnvironmentVariable : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE static QString value(const QString &name);
Q_INVOKABLE static void setValue(const QString &name, const QString &value);
Q_INVOKABLE static void unset(const QString &name);
};
// Define the singleton type provider function (callback).
QObject *qmlenvironmentvariable_singletontype_provider(QQmlEngine *, QJSEngine *);
#endif // QMLENVIRONMENTVARIABLE_H
QmlEnvironmentVariable.cpp
#include "QmlEnvironmentVariable.h"
#include <stdlib.h>
QString QmlEnvironmentVariable::value(const QString& name)
{
return qgetenv(qPrintable(name));
}
void QmlEnvironmentVariable::setValue(const QString& name, const QString &value)
{
qputenv(qPrintable(name), value.toLocal8Bit());
}
void QmlEnvironmentVariable::unset(const QString& name)
{
qunsetenv(qPrintable(name));
}
QObject *qmlenvironmentvariable_singletontype_provider(QQmlEngine *, QJSEngine *)
{
return new QmlEnvironmentVariable();
}
然后main()
添加对qmlRegisterSingletonType的调用(或者如果您正在创建插件,则在您重新实现的 QQmlExtensionPlugin::registerTypes()方法中):
#include "QmlEnvironmentVariable.h"
#include <QQmlEngine>
// ...
qmlRegisterSingletonType<QmlEnvironmentVariable>("MyModule", 1, 0,
"EnvironmentVariable", qmlenvironmentvariable_singletontype_provider);
最后,像这样在 QML 中使用它:
import MyModule 1.0
Item {
Component.onCompleted: console.log("My home directory: " + EnvironmentVariable.value("HOME"))
}
You would have to get the Username in C++ and then exchange that data from C++ to qml.
Read here how to exchange data between qml and C++.
我的解决方案是这样的:
1.)config.h
使用类创建文件Config
:
#ifndef CONFIG_H
#define CONFIG_H
#include <QString>
#include <QObject>
#include <QStandardPaths>
class Config : public QObject
{
Q_OBJECT
public:
explicit Config(QObject *parent = nullptr) {}
Q_INVOKABLE QString getHome() {
return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
}
};
#endif // CONFIG_H
2.)setContextProperty(...)
在你的设置main.cpp
int main(int argc, char *argv[]) {
...
Config config;
viewer.rootContext()->setContextProperty("config", config);
}
然后你可以简单地调用config.getHome()
你的 qml-js 文件。