Donnerstag, 7. Mai 2015

Qt: Poweroff System

I'm currently working on an embedded project and wanted to have an option to poweroff the system with a keyboard shortcut. The system is using systemd as init-system.

The following two functions show how you can call the poweroff function:
 void MainWindow::poweroff()  
 {  
   QDBusConnection system = QDBusConnection::systemBus();  
   if (!system.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.systemd1",  
                          "/org/freedesktop/systemd1",  
                          "org.freedesktop.systemd1.Manager",  
                          "PowerOff");  
   QDBusConnection::systemBus().asyncCall(message);  
 }  
 void MainWindow::poweroff_2()  
 {  
   QProcess *process = new QProcess(this);  
   QString program = "systemctl";  
   QStringList arguments("poweroff");  
   process->start(program, arguments);  
 }  
The first function will send a dbus message to systemd to poweroff the system while the second function will execute the systemctl command with poweroff as argument.

$ gdbus introspect --system --dest org.freedesktop.systemd1 --object-path /org/freedesktop/systemd1 will give you a nice overview of the available interface and methods available for systemd.

To assign a shortcut you can use the following functions (I'm calling these two functions in the constructor of my MainWindow class):
   new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F4), this, SLOT(poweroff()));  
   new QShortcut(QKeySequence(Qt::ALT + Qt::Key_F4), this, SLOT(poweroff_2()));  

Keine Kommentare:

Kommentar veröffentlichen