Qt5获取当前用户名

 Qt版本 : Qt5.12.8

#include <QDir>
#include <QStandardPaths>
#include <QProcess>

QString getCurrentUserName()
{
    QString userName;

    if (userName.isEmpty()) {
        QStringList envList = QProcess::systemEnvironment();
        for (const QString& env : envList) {
            if (env.startsWith("USERNAME")) {
                QStringList strList = env.split('=');
                if (strList.size() > 2) {
                    userName = strList[1];
                }
            }
        }
    }

    if (!userName.isEmpty()) {
        return userName;
    }

#if defined(Q_OS_WIN)
    userName = QStandardPaths::displayName(QStandardPaths::HomeLocation);
#elif defined(Q_OS_LINUX)
    QProcess process;
    process.start("whoami", QStringList());
    process.waitForFinished();
    userName = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed();
#endif

    return userName.isEmpty() ? QString("User") : userName;
}

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页