在运行时将更改环境变量应用于应用程序

Apply changed environment variables to QApplication at runtime

我正在尝试 运行

qputenv("QT_DEBUG_PLUGINS", "1");

在 QT 应用程序的 MainWindow 进行评估后的 运行 时间。

我假设要实际应用新的环境变量,我必须关闭初始化的 QApplication 并重新启动它,但我无法使其工作。

#include <QApplication>
#include "mainwindow.h"


int main(int argc, char *argv[])
{
    int exitCode = 0;
    do
    {
        //exitCode = EXIT_CHANGE_DEBUG_FLAG; //This will make it ALWAYS work

        //Double-checking for testing only, still does not work.
        if(exitCode == EXIT_CHANGE_DEBUG_FLAG)
        {
            qputenv("QT_DEBUG_PLUGINS", "1"); // Code does fire on 2nd pass, new app/window still ignores it
        }
        QApplication app(argc, argv);
        MainWindow mainWindow;
        mainWindow.show();
        exitCode = app.exec();
        //We can't change this once the app has been established.
        qputenv("QT_DEBUG_PLUGINS", "1");
        exitCode = EXIT_CHANGE_DEBUG_FLAG; //for testing only
    }
    while(exitCode == EXIT_CHANGE_DEBUG_FLAG);
    return(exitCode);
}

应用程序确实会重新启动,但它的行为并不像设置了 QT_DEBUG_PLUGINS 一样。如果我将该行移至 QApplication 上方,它始终有效,但我希望这是一个在 运行 时间可用的配置选项。

我觉得我要么在尝试做不可能的事情,要么我忽略了一些愚蠢的事情。

您可以在程序执行的任何时候设置环境变量,进一步调用 qgetenv 将 return 新值。您不必丢弃并重新创建您的 QApplication。只需在用户选择该配置选项时设置环境变量,它将在应用程序的其余执行时间内生效。

我认为您对 "application" 和 QApplication 是什么感到困惑。 QApplication 是应用程序中的一个对象。丢弃 QApplication 对象并创建一个新对象不会重新启动整个应用程序。

这可能与您的应用程序在启动时继承环境的想法有关,并且在您停止应用程序之前对应用程序外部环境所做的更改不会生效。但是,在这种情况下,qputenv 调用正在更新您的应用程序的环境副本。它不会改变您最初继承的外部环境。