Reputation: 2722
I need to know how to get the user name and/or home directory of the users. I've googled around for a while but can only find the variables for C++ or BASH.
How do I get the user name or home directory? I'm writing in QML.
Upvotes: 3
Views: 3400
Reputation: 5468
My solution was like this:
1.) create config.h
file with the Config
class:
#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.) set the setContextProperty(...)
in your main.cpp
int main(int argc, char *argv[]) {
...
Config config;
viewer.rootContext()->setContextProperty("config", config);
}
Then you can simply call config.getHome()
in your qml-js file.
Upvotes: 0
Reputation: 1967
This is how I implemented it:
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();
}
Then in main()
add a call to qmlRegisterSingletonType (or in your re-implemented QQmlExtensionPlugin::registerTypes() method if you're creating a plugin):
#include "QmlEnvironmentVariable.h"
#include <QQmlEngine>
// ...
qmlRegisterSingletonType<QmlEnvironmentVariable>("MyModule", 1, 0,
"EnvironmentVariable", qmlenvironmentvariable_singletontype_provider);
Finally, use it in QML like so:
import MyModule 1.0
Item {
Component.onCompleted: console.log("My home directory: " + EnvironmentVariable.value("HOME"))
}
Upvotes: 8
Reputation: 4858
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++.
Upvotes: 3