Qt World Summit: Submit your Presentation

How to get the name of a variable ?

  • Is there a way to get the name of a variable?
    I want to make it a function.

    Below is the source code I tried.

        QString hello = "World!";
        qDebug() << getVarName(&hello); // I want result : "hello"
    #define VAR_TO_STR(name) #name
    QString getVarName(QString *var)
        return VAR_TO_STR(var);

    I want code that can get the name and value of a variable at the same time.

  • Sorry, could I ask you why do you need this? Which is the situation that requires this?

  • I asked for convenience and curiosity.
    It is not absolutely necessary.

    Below is the cause of this problem.

    Setting::Setting(QWidget *parent) :
        ui(new Ui::Dialog)
        settings = new QSettings("Setting.ini",QSettings::IniFormat);
    void Setting::setDefault(QString *var,QString name,QString val)
        *var = settings->value(name).toString();

    The setDefault function is simple, but iterative.
    So I was thinking of a way to make it simpler.

  • Qt Champions 2017

    what is iterative inside setDefault function ? It is just one if condition. Did you miss something here ?

  • The function itself is not iterative, but the function is used repeatedly.

    Even if I use the source that I created, it does not interfere with the operation.

    However, you must use more than 100 'setDefault'.

    I want to minimize the possibility of mistakes because I have little experience with the program.

  • Thank you for answer.
    I will do it the before way if there is no way to get the name.

  • Qt Champions 2017

    No way to get the variable name. Also no use from getting the name of the variable. What matters is the value. You must work on the value rather than the variable name.

  • QDebug() << QT_STRINGIFY(MainWindowVM);

    QDebug QDebug(nullptr);
    QDebug << QT_STRINGIFY(QDebug);

Log in to reply