Implement Qt program under Linux to realize self-starting at boot

1.Principle

If you want to realize self-starting at boot, first of all, QT does not have this implementation. It is best to start the software in the startup directory when the computer is started. The following directory

/etc/xdg/autostart

This is the directory used to configure startup items in the operating system. This directory stores the launcher (.desktop) file that starts automatically at boot. If you want the software to start automatically at boot, it is mostly achieved by configuring a launcher file. You can see Check this directory

It stores a lot of configurations that need to be started at startup.

Therefore, if the QT program we write wants to realize self-starting, we can write a launcher (.desktop) file for this program and place it in this directory.

2. Realize

So how to achieve it?

It’s actually not difficult, just a few lines of code, as shown below

[Desktop Entry]
Exec=/home/yicaobao/qtProjects/SelfStartDemo/bin/bin/SelfStartDemo
Icon=/home/yicaobao/qtProjects/SelfStartDemo/bin/resource/start-logo.png
Name=SelfStartDemo
Terminal=false
Type=Application
X-Deepin-Vendor=user-custom

Let’s briefly introduce the main ones:

1.Exec: Path of the thing to be run (program, script, etc.)

2.Name: The name of the desktop file, the name of the launcher displayed in the /etc/xdg/autostart directory

3.Type: used to specify the type of desktop file (including 3 types: Application, Link, Directory).

4.Icon: desktop file has no icon

        Icon: Specify the full path of the application icon (the suffix can be omitted).

        Icons support png format, svg format, etc. The recommended size of the icon is 128x128.

So a basic desktop file template would look like this:

[Desktop Entry]

Name=<Application Name>

Type=Application

Exec=<Full path to application>

Icon=<Full path to application icon>

I quoted it from here:https://www.ywnz.com/linuxjc/3603.html, you need to know more You can go take a look

So we just need to write a launcher and throw it into the startup directory.

In fact, it’s not too troublesome, but it’s not very convenient. But if you want to be smarter, it would be better if you write an option in the program and check it to realize automatic startup or cancel automatic startup, like this

3.QT code implementation

The idea is as follows, first write a launcher, and then write a script program for self-starting and canceling self-starting at boot. The script will copy the launcher to the Linux startup directory.

So it is used in QT to write files and execute script modules.

Explain the core code:

1. Get the name of the current program because it is needed for startup

AppName = QCoreApplication::applicationName();

2. Start the script directory

    QDir dir(QCoreApplication::applicationDirPath());
    dir.cdUp();
    startFileDir =  dir.path();

3. Generate launcher code

void Widget::generateStartFile(QString fileName)
{
    QString filePath =  startFileDir + "/" + fileName;
    QFile File(filePath);
    if(File.exists()) {
        //return;
    }
    QString startFilePath;
    QStringList list;

    list << "[Desktop Entry]"
         << QString("Exec=%1/bin/%2").arg(startFileDir).arg(AppName)
         << QString("Icon=%1/resource/start-logo.png").arg(startFileDir)
         << QString("Name=%1").arg(AppName)
         << "Terminal=false"
         << "Type=Application"
         << "X-Deepin-Vendor=user-custom";
    //写入到文件中
    writeStartFile(filePath, list);
}

4. Generate a shell script that copies the launcher file to the startup directory under Linux

void Widget::copyToAutostartShell(QString desktopName)
{
    QStringList arguments;

    arguments << "#!/bin/sh"
         << QString("#设置开机自动启动")
         << QString("echo \"%1\" | sudo -S cp %2 /etc/xdg/autostart").arg(userPwd).arg(startFileDir+'/'+desktopName)
         << QString("notify-send \"程序已设置开机自启动\"");
    //写入到文件中
    writeStartFile(startFileDir+"/AotuStart.sh", arguments);
}

5. Generate a script to remove the launcher file, that is, cancel the startup

void Widget::removeAutostartFile(QString desktopName)
{
    QStringList arguments;

    arguments << "#!/bin/sh"
         << QString("echo \"%1\" | sudo -S rm /etc/xdg/autostart/%2").arg(userPwd).arg(desktopName)
         << QString("notify-send \"程序开机自启动已取消\"");

    writeStartFile(startFileDir+"/unAotuStart.sh", arguments);
}

6. Code that executes the script

void Widget::executeLinuxCmd(QString path, QString fileName)
{
    QProcess *backupProcess = new QProcess;
    backupProcess->setWorkingDirectory(path);
    backupProcess->start("/bin/sh",QStringList()<<fileName);
    bool isfinished = backupProcess->waitForFinished();
    QString strResult = backupProcess->readAllStandardOutput();
    QString strErrResult = backupProcess->readAllStandardError();
    //QStringList strList = strResult.split("\n");
    if(!strErrResult.isEmpty()) {
        QMessageBox::information(this, "提示", strResult);
    }
    else {
        QMessageBox::information(this, "提示", strResult);
    }

    if(isfinished){
        backupProcess->close();
        delete backupProcess;
        backupProcess = nullptr;
    }
}

Click to select the code to start automatically at startup or cancel the code for automatic startup at startup.

void Widget::on_selfStart_stateChanged(int state)
{
    Q_UNUSED(state)
    UserPwdDialog dialog(this);
    if (QDialog::Accepted != dialog.exec())
        return;
    userPwd = dialog.getPWD();

    if(ui->selfStart->isChecked()) {
        generateStartFile(QString("%1.desktop").arg(AppName));
        copyToAutostartShell(QString("%1.desktop").arg(AppName));
        executeLinuxCmd(startFileDir, "AotuStart.sh");
    }
    else {
        removeAutostartFile(QString("%1.desktop").arg(AppName));
        executeLinuxCmd(startFileDir, "unAotuStart.sh");
    }
}

4. Effect

The effect after setting auto-start at boot is as follows. Restart the computer and you will find that the program will start up.

The effect after setting to cancel boot auto-start is as follows. If you delete the launcher file, it will not start at boot.

I am just giving a simple example. Based on this example, you can understand it and make an interface. Then, you can use it for programs that want to start automatically at boot.

Let me give you the source code of this example:

Contact: https://pan.baidu.com/s/1Yn_N87IKgjKUerVhb5GtUQ Delivery: 8888 

The QT program under Linux starts automatically after booting. Use code to intelligently start or cancel it. After searching for a long time, I couldn't find one on the Internet, ૮₍ ◞‸◟₎ა. Later, I found some time to understand this principle and got it. Here is an example. If it is helpful to you, remember to give it a like and let me see if many people want this kind of functional code.

Or if you have any better solutions or other questions, please comment and leave a message to discuss ੭ ᐕ)੭

Guess you like

Origin blog.csdn.net/qq_44667165/article/details/134692485