程序思路
- 给qApp安装事件过滤器
- 开启定时器监视屏幕激活标志位
源码下载
https://gitee.com/jiang_bin_yu/sleep_wakeup/tree/master/
程序执行效果
程序源码
代码展示
一、给qApp安装事件过滤器;
a.自定义触发器
bool MyApplication::screenWake = true; //全局标志位 表示是否屏幕被激活
MyApplication::MyApplication(int & argc, char ** argv) : QApplication(argc, argv)
{
qDebug() << "MyApplication";
}
bool MyApplication::notify(QObject *receiver, QEvent *e)
{
//捕捉按键按下事件
if(e->type() == QEvent::MouseButtonPress) //receiver->parent() != NULL &&
{
screenWake = true;
QMouseEvent *mouseEvent=static_cast<QMouseEvent *>(e);
qDebug() << "MouseButtonPress" << receiver->objectName() << screenWake << &screenWake;
}
return QApplication::notify(receiver, e);
}
b.安装事件过滤器
#include "mainwindow.h"
#include <QApplication>
#include "myapplication.h"
int main(int argc, char *argv[])
{
//QApplication a(argc, argv);
MyApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
二、开启定时器监视屏幕激活标志位
void MainWindow::onSleepTimeout()
{
static int misoperationTime = 0; //无操作时间
//屏幕被触发 重新进入待机倒计时
qDebug() << "onSleepTimeout" << MyApplication::screenWake;
if(MyApplication::screenWake)
{
MyApplication::screenWake = false;
misoperationTime = 0;
}
ui->label->setText(QString("还有%1秒后进入待机页面").arg(QString::number(sleepTime-misoperationTime)));
if(misoperationTime == sleepTime)
{
mainBackGroud dlg; //进入休眠页面
dlg.exec();
misoperationTime = 0;
}
misoperationTime++;
}
三、自定义待机界面,当点击开始按钮后退出待机页面
mainBackGroud::mainBackGroud(QWidget *parent)
: QDialog(parent),
ui(new Ui::mainBackGroud)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint); //无边框
//this->setFixedSize(SCR_WIDTH,SCR_HEIGHT);
QPalette palette;
palette.setBrush(this->backgroundRole(),QBrush(QColor(77,220,137)));//设置背景
setPalette(palette);
ui->pushButton_start->setStyleSheet("QPushButton{font-size: 60px;\
font-family: \"思源黑体 CN bold\",\"思源黑体 CN\";\
font-weight: bold;color: #203864;\
border-image:url(:/mainclass/Resource/MainClass/welcome-btn.png);background-color:transparent;} \
QPushButton::pressed{padding-left:12px; padding-top:12px;}\
QPushButton::checked{padding-left:12px; padding-top:12px;}\
QPushButton::hover{padding-left:7px; padding-top:7px;}");
}
//进入主界面
void mainBackGroud::on_pushButton_start_clicked()
{
done(QMessageBox::Ok);
close();
}