On linux / X11, you can learn about the user inactivity time through the screensaver API (screensaver).
On the development machine, install libxss-dev :
$ sudo apt-get install libxss-dev
Add to the .pro file
LIBS += -lX11 -lXss
In the new project, the default code is as follows:
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void checkIdle(); private: void logout(); Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QTimer> #include <X11/extensions/scrnsaver.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); checkIdle(); // Π·Π°ΠΏΡΡΠΊΠ°Π΅ΠΌ ΠΎΡΡΠ»Π΅ΠΆΠΈΠ²Π°Π½ΠΈΠ΅ } MainWindow::~MainWindow() { delete ui; } void MainWindow::checkIdle() // ΠΎΡΡΠ»Π΅ΠΆΠΈΠ²Π°Π½ΠΈΠ΅ ΠΏΠ΅ΡΠΈΠΎΠ΄Π° Π±Π΅Π·Π΄Π΅ΠΉΡΡΠ²ΠΈΡ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ { static Display *display = XOpenDisplay(NULL); if (display == NULL) { return; } static XScreenSaverInfo *info = XScreenSaverAllocInfo(); XScreenSaverQueryInfo(display, DefaultRootWindow(display), info); const int targetIdleMs = 5 * 1000; // ΡΠ΅Π»Π΅Π²ΠΎΠ΅ Π²ΡΠ΅ΠΌΡ Π±Π΅Π·Π΄Π΅ΠΉΡΡΠ²ΠΈΡ Π² ΠΌΠΈΠ»Π»ΠΈΡΠ΅ΠΊΡΠ½Π΄Π°Ρ
const int actualIdleMs = info->idle; // ΡΠ°ΠΊΡΠΈΡΠ΅ΡΠΊΠΎΠ΅ Π²ΡΠ΅ΠΌΡ Π±Π΅Π·Π΄Π΅ΠΉΡΡΠ²ΠΈΡ Π² ΠΌΡ if (actualIdleMs < targetIdleMs) { // ΠΆΠ΄Π΅ΠΌ ΠΎΡΡΠ°Π²ΡΠ΅Π΅ΡΡ Π²ΡΠ΅ΠΌΡ Π΄ΠΎ ΡΠ΅Π»Π΅Π²ΠΎΠ³ΠΎ ΠΈ ΠΏΠΎΡΠΎΠΌ ΡΠ½ΠΎΠ²Π° ΠΏΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ QTimer::singleShot(targetIdleMs - actualIdleMs, this, SLOT(checkIdle())); } else { // ΡΠ΅Π»Π΅Π²ΠΎΠ΅ Π²ΡΠ΅ΠΌΡ Π΄ΠΎΡΡΠΈΠ³Π½ΡΡΠΎ logout(); } } void MainWindow::logout() // ΠΆΠ΅Π»Π°Π΅ΠΌΡΠ΅ Π΄Π΅ΠΉΡΡΠ²ΠΈΡ ΠΏΡΠΈ Π±Π΅Π·Π΄Π΅ΠΉΡΡΠ²ΠΈΠΈ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ { close(); }
For clarification. Added two features
private slots: void checkIdle(); private: void logout();
Added to .cpp
#include <QTimer> #include <X11/extensions/scrnsaver.h>
From the constructor, call checkIdle() . In it, the targetIdleMs constant targetIdleMs target inactivity time, compare it with the actual and wait on the timer until the next check. At the next check, if the required period was not formed, we again wait; otherwise, call logout() , which in this case closes the program.