前面我们用继承QApplication的方式实现了屏幕保护,

接下了用第二种方式:

首先定义一个屏保类:



#ifndef SPLASHSCREEN_H #define SPLASHSCREEN_H #include <QWidget> #include "mainwindow.h" namespace Ui { class SplashScreen; } class SplashScreen : public QWidget { Q_OBJECT public: explicit SplashScreen(QWidget *parent = 0); ~SplashScreen(); protected: void keyPressEvent(QKeyEvent *e); private: Ui::SplashScreen *ui; }; #endif // SPLASHSCREEN_H


cpp.文件




#include "splashscreen.h" #include "ui_splashscreen.h" #include <QImage> #include <QDebug> SplashScreen::SplashScreen(QWidget *parent) : QWidget(parent), ui(new Ui::SplashScreen) { ui->setupUi(this); QImage *image = new QImage(":/style/ui_image/load.png"); ui->label->setPixmap(QPixmap::fromImage(*image)); } SplashScreen::~SplashScreen() { delete ui; } void SplashScreen::keyPressEvent(QKeyEvent *e) { this->hide(); ((MainWindow*)this->parentWidget())->currentWidgetChanged(3); }

主函数中:

QApplication app(argc, argv); 

MainWindow mainWin;mainWin.show();

app.installEventFilter(&mainWin);return app.exec();

将mainWin注册一个焦点过滤事件,写一个定时器的槽函数


mainwindow.h文件中添加:



private slots: 

void splashTimeTimeoutSlot();

protected:bool eventFilter(QObject *obj, QEvent *event);

private:



QWidget *pSplashTimeWidget = Q_NULLPTR; 
//定义一个计时器,多久进入屏幕保护


QTimer splashTime; //重写过滤事件函数
mainwindow.cpp文件中实现两个函数:
在mainwindow的构造函:
pSplashTimeWidget = new SplashScreen(this);pSplashTimeWidget->hide();

connect(&splashTime,SIGNAL(timeout()),this,SLOT(splashTimeTimeoutSlot()));

//实例化并隐藏
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{


if (event->type() == QEvent::KeyPress) {// if(sysInfo.sleeptime = "")// {splashTime.start(5000);

}return QObject::eventFilter(obj, event);
}


void MainWindow::splashTimeTimeoutSlot()
{ pSplashTimeWidget->show();pSplashTimeWidget->grabKeyboard();
}