Evgenii Legotckoi
Feb. 15, 2016, 9:07 p.m.

Qt Linux - Lesson 001. Autorun Qt application under Linux

Let's talk about how you can add functionality in Qt application to configure startup of the application. For example, we have a settings window, and we want to make the ability to customize the dialog box Autorun application.

In contrast to the autorun in Windows , where you can use QSettings and make changes to the registry on Linux you need to create a custom executable file that will be responsible for autostart applications when a user logs into the operating system.

Say the name of the project and hence the name of the executable file will AutorunLinux , then you need to create an executable file AutorunLinux.desktop the following path:

  1. ~/.config/autostart/AutorunLinux.desktop

The contents of the executable file to do the same to other startup files of other applications that are guaranteed to get the desired result. In the case of Ubuntu Linux 15.04 / 15.10 contents of the file will receive the following:

  1. [Desktop Entry]
  2. Type=Application
  3. Exec=/home/dekadent/QT/Projects/build-AutorunLinux-Desktop_Qt_5_5_1_GCC_64bit-Debug/AutorunLinux
  4. Hidden=false
  5. NoDisplay=false
  6. X-GNOME-Autostart-enabled=true
  7. Name[en_GB]=AutorunLinux
  8. Name=AutorunLinux
  9. Comment[en_GB]=AutorunLinux
  10. Comment=AutorunLinux

Where Exec parameter specifies the path to the executable file.

Also, do not forget to make the file executable:

  1. chmod +x ~/.config/autostart/AutorunLinux.desktop

To be guaranteed to ensure correct startup file contents being prepared, I recommend to start to add your application to autostart with a standard utility Startup Applications .

This utility will create a guaranteed working version of the file for your application. Then you just need to add content through the code with an automatic modification of the path to the executable file.

Project structure

To demonstrate the code, I suggest the following to create a project with the following contents:

  • AutorunLinux.pro - the profile of the project;
  • widget.h - header file of the main application window;
  • widget.cpp - file source code of the main application window;
  • widget.ui - form the main application window;
  • main.cpp - the main file of the application source code.

This application will be a checkbox, as we will delete and add applications to the startup by pressing the PushButton button. When running the application will pop up a message that the application is running. The appearance of the application as follows:

widget.h

In the header file of all the changes will be only ad slot to press the button:

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. namespace Ui {
  7. class Widget;
  8. }
  9.  
  10. class Widget : public QWidget
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit Widget(QWidget *parent = 0);
  16. ~Widget();
  17.  
  18. private slots:
  19. void on_pushButton_clicked();
  20.  
  21. private:
  22. Ui::Widget *ui;
  23. };
  24.  
  25. #endif // WIDGET_H

widget.cpp

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3. #include <QMessageBox>
  4. #include <QDir>
  5. #include <QFile>
  6. #include <QTextStream>
  7. #include <QStandardPaths>
  8.  
  9. Widget::Widget(QWidget *parent) :
  10. QWidget(parent),
  11. ui(new Ui::Widget)
  12. {
  13. ui->setupUi(this);
  14. QMessageBox::information(this,"AutoRun","Apllication is started!");
  15. }
  16.  
  17. Widget::~Widget()
  18. {
  19. delete ui;
  20. }
  21.  
  22. void Widget::on_pushButton_clicked()
  23. {
  24. // Path to the autorun folder
  25. QString autostartPath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).at(0) + QLatin1String("/autostart");
  26. /* Check whether there is a directory in which to store the autorun file.
  27.      * And then you never know ... user deleted ...
  28. * */
  29. QDir autorunDir(autostartPath);
  30. if(!autorunDir.exists()){
  31. // Если не существует, то создаём
  32. autorunDir.mkpath(autostartPath);
  33. }
  34. QFile autorunFile(autostartPath + QLatin1String("/AutorunLinux.desktop"));
  35. /* Check the state of the checkbox, if checked, adds the application to the startup.
  36.      * Otherwise remove
  37. * */
  38. if(ui->checkBox->isChecked()) {
  39. // Next, check the availability of the startup file
  40. if(!autorunFile.exists()){
  41.  
  42. /* Next, open the file and writes the necessary data
  43.              * with the path to the executable file, using QCoreApplication::applicationFilePath()
  44. * */
  45. if(autorunFile.open(QFile::WriteOnly)){
  46.  
  47. QString autorunContent("[Desktop Entry]\n"
  48. "Type=Application\n"
  49. "Exec=" + QCoreApplication::applicationFilePath() + "\n"
  50. "Hidden=false\n"
  51. "NoDisplay=false\n"
  52. "X-GNOME-Autostart-enabled=true\n"
  53. "Name[en_GB]=AutorunLinux\n"
  54. "Name=AutorunLinux\n"
  55. "Comment[en_GB]=AutorunLinux\n"
  56. "Comment=AutorunLinux\n");
  57. QTextStream outStream(&autorunFile);
  58. outStream << autorunContent;
  59. // Set access rights, including on the performance of the file, otherwise the autorun does not work
  60. autorunFile.setPermissions(QFileDevice::ExeUser|QFileDevice::ExeOwner|QFileDevice::ExeOther|QFileDevice::ExeGroup|
  61. QFileDevice::WriteUser|QFileDevice::ReadUser);
  62. autorunFile.close();
  63. }
  64. }
  65. } else {
  66. // Delete the startup file
  67. if(autorunFile.exists()) autorunFile.remove();
  68. }
  69. }

Conclusion

As a result of the application of this code will make itself to the startup and run when a user logs into the system. To test performance, create an application using the autorun file, log out and log in again (Log Out/ Log In).

The source code of the project: AutorunLinux

Do you like it? Share on social networks!

a
  • Sept. 21, 2018, 3:08 p.m.

Спасибо за статью!

Пример рабочий! Со своим проектом тоже получилось!


Наткнулся на эту статью когда решал задачу запуска Qt app с помощью .

Когда пробовал с помощью получилось запустить простой проект Qt с QCoreApplication. Т.е. без gui.

Для этого оказалось достаточно создать файл (в моем случае) в /etc/systemd/system/

[Unit]
Description=qt_console_app service desription

[Service]
ExecStart=/home/user/cpp_examples/build/build_qt_console_app/qt_console_app
Restart=always

[Install]
WantedBy=graphical.target

И запустить:


Но если хочу запускать проект Qt с gui - не получается!

С помощью видно ошибку:

QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
сен 21 11:29:44 debian systemd-demo[11389]: qt.qpa.screen: QXcbConnection: Could not connect to display
сен 21 11:29:44 debian systemd-demo[11389]: Could not connect to any X display.

Пытался играться с переменными DISPLAY и с Xauthority. Но воз и ныне там.

Только что на линуксовой форуме прочитал, что не для приложений с gui. Там советуют пользоваться средствами автозапуска. Это, скорее-всего, и есть тема данной статьи, которая сработало.

Не подскажете, может ли есть какой-то путь, хитрости, чтобы, всё-таки, запустить проект Qt с GUI с помощью ?


И второй вопрос. Через пробовал в том числе потому что нужен рестарт приложения, если упадет. Там всего-лишь дописывается одна строчка в вышеприведенный файл.

И с помощью Вашего подхода можно ли как-то дописать авторестарт при падение программы?

Evgenii Legotckoi
  • Sept. 21, 2018, 3:24 p.m.

Если я вас правильно понял, то авторестарт сюда дописывается  QString autorunContent.
Не могли бы вы не выделять пока слова жирным текстом, в комментариях сломан парсинг тегов, завтра буду чинить. Поэтому съедаются жирные слова.

a
  • Sept. 24, 2018, 8:40 p.m.

Не могли бы подробнее рассказать об этой возможности? Я докопался до запросов Desktop Entry Files + restart, но до сих пор не найду autorunContent, о котором Вы писали...

Evgenii Legotckoi
  • Sept. 24, 2018, 8:42 p.m.

Ну я имел ввиду, что дописать в коде вот сюда то, о чём вы говорили про рестарт

  1. QString autorunContent("[Desktop Entry]\n"
  2. "Type=Application\n"
  3. "Exec=" + QCoreApplication::applicationFilePath() + "\n"
  4. "Hidden=false\n"
  5. "NoDisplay=false\n"
  6. "X-GNOME-Autostart-enabled=true\n"
  7. "Name[en_GB]=AutorunLinux\n"
  8. "Name=AutorunLinux\n"
  9. "Comment[en_GB]=AutorunLinux\n"
  10. "Comment=AutorunLinux\n");
a
  • Sept. 24, 2018, 8:47 p.m.

Просто сейчас правлю сам файл example.desktop. Пытаюсь понять какую пару key=value мне нужно дописать.

Evgenii Legotckoi
  • Sept. 24, 2018, 8:55 p.m.

Если честно, то я не уверен, что это вообще можно реализовать через *.desktop файл. Я сделал предположение на основе того, что вы сказали про *.desktop и рестарт.

Все варианты, которые встречаются на форумах, предполагают наличие демона, который следит за тем, чтобы программа была онлайн.

Например я использую supervisor для автостарта сервисов сайта. Поэтому перезагрузка скриптов сайта у меня делается через killall. Грубовато, но supervisor ещё ни разу не подводил.



a
  • Sept. 24, 2018, 9 p.m.

Не могли бы дать ссылку на пример? Какое-то рабочее использование. Т.е. у меня есть Qt Gui App, которое я бы хотел запускать при старте системы и в случае, если оно грохнется. Если о чем Вы говорите это поможет сделать, не могли бы просвятить в виде ссылки или примерного направление копания))

Evgenii Legotckoi
  • Sept. 24, 2018, 9:09 p.m.

А вот здесь у меня есть пример использования supervisor.

https://evileg.com/ru/post/3/

Вся статья вам там не интересна, интересен только шаг с настройкой supervisor. Он получается будет у вас как зависимость к вашему приложению, но вопрос зависимостей - это уже отдельная тема для разговора. В данном случае к самому программированию supervisor отношения не имеет. Это настройка демона.


a
  • Sept. 27, 2018, 9:07 p.m.

Спасибо! На данный момент выбор пал в сторону скрипта с бесконечным циклом, перегружающим программу при падение.

Здесь подробнее описал.

k
  • Feb. 9, 2024, 5:43 a.m.

как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html