Get $HOME and/or username in QML

2019-07-18 07:25发布

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.

标签: qml
3条回答
萌系小妹纸
2楼-- · 2019-07-18 07:59

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.

查看更多
该账号已被封号
3楼-- · 2019-07-18 08:04

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"))
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-18 08:11

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++.

查看更多
登录 后发表回答