Skip to content

Instantly share code, notes, and snippets.

@andreybutov
Last active February 17, 2023 04:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreybutov/33783bca1af9db8f9f36c463c77d7a86 to your computer and use it in GitHub Desktop.
Save andreybutov/33783bca1af9db8f9f36c463c77d7a86 to your computer and use it in GitHub Desktop.
How do I make my Qt app start automatically at login?
//
// How do I make my Qt app start automatically at login?
// This solution is for Windows and Mac. It was tested with Qt 5.5.
//
// - Andrey Butov ( andreybutov.com )
//
void setAppToStartAutomatically ( bool startAutomatically )
{
#if defined ( Q_OS_MAC )
// Remove any existing login entry for this app first, in case there was one
// from a previous installation, that may be under a different launch path.
{
QStringList args;
args << "-e tell application \"System Events\" to delete login item\""
+ macOSXAppBundleName() + "\"";
QProcess::execute("osascript", args);
}
// Now install the login item, if needed.
if ( startAutomatically )
{
QStringList args;
args << "-e tell application \"System Events\" to make login item at end " +
"with properties {path:\"" + macOSXAppBundlePath() + "\", hidden:false}";
QProcess::execute("osascript", args);
}
#elif defined ( Q_OS_WIN )
QString key = "YouApplicationName";
QSettings registrySettings(
"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
QSettings::NativeFormat);
registrySettings.remove(key);
if ( startAutomatically ) {
registrySettings.setValue(key, QString("\"" + windowsAppPath() + "\""));
}
registrySettings.sync();
#endif
}
QString macOSXAppBundlePath()
{
#ifdef Q_OS_MAC
QDir dir = QDir ( QCoreApplication::applicationDirPath() );
dir.cdUp();
dir.cdUp();
QString absolutePath = dir.absolutePath();
// absolutePath will contain a "/" at the end,
// but we want the clean path to the .app bundle
if ( absolutePath.length() > 0 && absolutePath.right(1) == "/" ) {
absolutePath.chop(1);
}
return absolutePath;
#else
return "";
#endif
}
QString macOSXAppBundleName()
{
#ifdef Q_OS_MAC
QString bundlePath = macOSXAppBundlePath();
QFileInfo fileInfo(bundlePath);
return fileInfo.baseName();
#else
return "";
#endif
}
QString windowsAppPath()
{
#ifdef Q_OS_WIN
return QDir::toNativeSeparators(QCoreApplication::applicationFilePath());
#else
return "";
#endif
}
@DracFiendMG
Copy link

DracFiendMG commented Dec 1, 2022

Where do I define my path at applicationFilePath() in line 85?

@andreybutov
Copy link
Author

@crazydev0206
Copy link

Hi, Thank you for your code.
Btw, I have some issue to run your code....
If possible, could you post real project(.pro) for me to run easily?
Thank you again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment