Determine if Qt App has a UI
I'm working on a large project that uses Qt. The application has the option of running both in GUI or batch modes, and I don't have access to that info where I am 开发者_JAVA百科at.
But, I do have access to the QApp. Is there a way to know through Qt if an UI exists or has been initialized?
QApplication
has a topLevelWidgets()
function that returns a list of top-level widgets. You could check if that list is empty or not.
Have you considered using QCoreApplication instead of QApplication, for the batch mode? You're not supposed to use QApplication for non-GUI applications.
If you do it this way, the qApp should either return a pointer to a QCoreApplication (non-GUI), or QApplication (GUI), which you can check at runtime (if you need to) with a dynamic_cast.
Depening on the operating system, you can look at environment variables to determine if showing a gui is even possible. In my Linux setup, if the environment variable DISPLAY
is set, a desktop environment is available. If I log in through ssh or boot in headless mode, the variable is not set.
This is not the optimal solution for David's answer, but it has the advantage of working independently of the QApp
object. For example, in my case it had to be determined before the app was initialized.
bool guiCanBeShown(void)
{
return !qgetenv("DISPLAY").isEmpty();
}
精彩评论