简体   繁体   English

在 Qt 中获取系统用户名

[英]Get system username in Qt

Is there any cross platform way to get the current username in a Qt C++ program?在 Qt C++ 程序中是否有任何跨平台的方式来获取当前用户名?

I've crawled the internet and the documentation for a solution, but the only thing I find are OS dependent system calls.我已经在互联网上搜索了解决方案的文档,但我发现的唯一内容是依赖于操作系统的系统调用。

I was actually thinking about it a couple of days ago, and I came to the conclusion of having different alternatives, each with its own trade-off, namely:几天前我实际上在考虑它,我得出结论,有不同的选择,每个都有自己的权衡,即:

Environment variables using qgetenv .使用qgetenv 的环境变量。

The advantage of this solution would be that it is really easy to implement.这种解决方案的优点是它真的很容易实现。 The drawback is that if the environment variable is set to something else, this solution is completely unreliable then.缺点是如果将环境变量设置为其他内容,则此解决方案是完全不可靠的。

#include <QString>
#include <QDebug>

int main()
{
    QString name = qgetenv("USER");
    if (name.isEmpty())
        name = qgetenv("USERNAME");
    qDebug() << name;
    return 0;
}

Home location with QStandardPaths使用QStandardPaths 的家庭位置

The advantage is that, it is relatively easy to implement, but then again, it can go unreliable easily since it is valid to use different username and "entry" in the user home location.优点是,它相对容易实现,但同样,它很容易变得不可靠,因为在用户家庭位置使用不同的用户名和“条目”是有效的。

#include <QStandardPaths>
#include <QStringList>
#include <QDebug>
#include <QDir>

int main()
{
    QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    qDebug() << homePath.first().split(QDir::separator()).last();
    return 0;
}

Run external processes and use platform specific APIs运行外部进程并使用特定于平台的 API

This is probably the most difficult to implement, but on the other hand, this seems to be the most reliable as it cannot be changed under the application so easily like with the environment variable or home location tricks.这可能是最难实现的,但另一方面,这似乎是最可靠的,因为它不能像使用环境变量或家庭位置技巧那样容易地在应用程序下更改。 On Linux, you would use QProcess to invoke the usual whoami command , and on Windows, you would use the GetUserName WinAPI for this purpose.在 Linux 上,您将使用QProcess来调用通常的whoami 命令,而在 Windows 上,您将为此使用GetUserName WinAPI

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char **argv)
{
// Strictly pseudo code!
#ifdef Q_OS_WIN
    char acUserName[MAX_USERNAME];
    DWORD nUserName = sizeof(acUserName);
    if (GetUserName(acUserName, &nUserName))
        qDebug << acUserName;
    return 0;
#elif Q_OS_UNIX
    QCoreApplication coreApplication(argc, argv);
    QProcess process;
    QObject::connect(&process, &QProcess::finished, [&coreApplication, &process](int exitCode, QProcess::ExitStatus exitStatus) {
        qDebug() << process.readAllStandardOutput();
        coreApplication.quit();
    });
    process.start("whoami");
    return coreApplication.exec();
#endif
}

Summary : I would personally go for the last variant since, even though it is the most difficult to implement, that is the most reliable.总结:我个人会选择最后一个变体,因为尽管它最难实现,但它是最可靠的。

There is no way to get the current username with Qt.无法使用 Qt 获取当前用户名。

However, you can read this links :但是,您可以阅读此链接:

http://www.qtcentre.org/threads/12965-Get-user-name http://qt-project.org/forums/viewthread/11951 http://www.qtcentre.org/threads/12965-Get-user-name http://qt-project.org/forums/viewthread/11951

I think the best method is :我认为最好的方法是:

#include <stdlib.h>

getenv("USER"); ///for MAc or Linux
getenv("USERNAME"); //for windows

EDIT : You can use qgetenv instead of getenv .编辑:您可以使用qgetenv而不是getenv

In QT5 and up it is possible to do the following :在 QT5 及更高版本中,可以执行以下操作:

QString userName = QDir::home().dirName();

` QDir::home() returns the user's home directory. ` QDir::home()返回用户的主目录。

You can use qEnvironmentVariable您可以使用qEnvironmentVariable

QString sysUsername = qEnvironmentVariable("USER");
if (sysUsername.isEmpty()) sysUsername = qEnvironmentVariable("USERNAME");

Also you can use QProcessEnvironment like this:您也可以像这样使用QProcessEnvironment

QProcessEnvironmentenv = QProcessEnvironment::systemEnviroment();
QString username = env.value("USER");

There is a way to get the current windows username with Qt.有一种方法可以使用 Qt 获取当前的 Windows 用户名。 Here it is这里是

mainwindow.ui This is the form ui mainwindow.ui这是表单ui

mainwindow.cpp主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDir>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->getUser();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::getUser()
{
    QProcess *username = new QProcess();
    QStringList cmdParamaters, split;
    QString clean1, clean2, clean3,userName;
    int cutOff, strLen;

    cmdParamaters << "/c"<<"\"%USERPROFILE%\"";
    username->setProcessChannelMode(QProcess::MergedChannels);
    username->start("cmd.exe",cmdParamaters);
    username->waitForFinished();

    QString vusername (username->readAllStandardOutput());
    cutOff = vusername.indexOf("'", 1);
    ui->label_2->setText(vusername);

    clean1 = vusername.left(cutOff);
    ui->label_3->setText(clean1);

    clean2 = clean1.remove(0,3);
    strLen = clean2.length();
    ui->label_4->setText(clean2);

    clean3 = clean2.left(strLen-2);
    split = clean3.split("\\");

    userName = split[2]; //This is the current system username
    ui->label_5->setText(userName);
    delete username;
}

Output: Code output输出:代码输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM