在运行时将更改的环境变量应用于 QApplication



我正在尝试运行

qputenv("QT_DEBUG_PLUGINS", "1");

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

我假设要实际应用新的 env var,我必须关闭初始化的 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 将返回新值。您不必放弃并重新创建 QApplication。只需在用户选择该配置选项时设置环境变量,它将在应用程序的剩余执行时间内生效。

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

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

最新更新