龙空技术网

从零开始学Qt(49):进阶!自定义splash窗口

未来奇兵 401

前言:

当前姐妹们对“qt程序自启动”大致比较讲究,看官们都想要剖析一些“qt程序自启动”的相关文章。那么小编也在网上搜集了一些有关“qt程序自启动””的相关资讯,希望朋友们能喜欢,兄弟们快快来了解一下吧!

初始(splash)屏幕是通常在启动应用程序时显示的组件。初始屏幕通常用于启动时间较长的应用程序(例如,需要时间建立连接的数据库或网络应用程序),以向用户提供应用程序正在加载的反馈。

Qt提供了QSplashScreen类用作应用程序启动时的splash窗口,但仅提供了最基本的功能。想要更强大的splash功能,可以自定义splash窗口。本文对此进行介绍。

自定义splash窗口界面

采用新建Qt Designer Form Class的方法创建splash窗口,它从QWidget继承而来,设置类名称为FormSplash。

界面设计在UI设计器里进行,主要区域是一个显示图片的QLabel组件,通过文件载入图片,为QLabel组件的pixmap指定图片。

图片下方放置一个QListWidget组件,用于信息输出。组件垂直布局分布。界面如下图所示:

自定义splash的设计界面

自定义splash类功能

(1)窗口属性设置

构造函数内添加如下代码,设置窗口的属性:

this->setAttribute(Qt::WA_DeleteOnClose); // 设置为关闭时删除this->setWindowFlags(Qt::SplashScreen); // 设置为SplashScreenthis->setWindowModality(Qt::ApplicationModal); // 设置为模态显示

使用setWindowFlags()函数将窗口标志设置为Qt::SplashScreen,这样窗口显示为Splash窗口,无边框,且在Windows任务栏上没有显示。

使用setWindowModality()函数将窗口模态设置为Qt::ApplicationModal,这样窗口对于整个程序是模态显示的,始终在前端显示,且关闭前不能操作主窗口。

(2)splash窗口定时关闭

在FormSplash类中定义一个QTimer对象指针timer,

private:	QTimer *timer;public:	void startTimer();

timer的初始化代码为

timer=new QTimer(this);timer->setSingleShot(true);connect(timer,SIGNAL(timeout()),this,SLOT(close()));

函数setSingleShot()将定时器设置为单次触发。通过connect()函数,将定时器的timeout()信号连接到窗口的close(),表示定时器定时结束后后关闭窗口。

startTimer()函数定义为,

void FormSplash::startTimer(){	timer->start(3000);}

调用startTimer()启动定时器,时间间隔设置为3000 ms。

(3) splash窗口鼠标点击关闭

利用鼠标事件进行处理。在类定义中添加mousePressEvent()函数定义,

private:	void mousePressEvent(QMouseEvent *event);

函数实现代码为,

void FormSplash::mousePressEvent(QMouseEvent *event){	Q_UNUSED(event);	this->close();}

(4) splash窗口信息输出

定义了1个dispInfo()函数,

void FormSplash::dispInfo(QString str){	ui->listWidget->insertItem(0,str);}

调用此函数,可以在Splash窗口listWidget组件中插入一条信息。

splash窗口的调用

设计好窗口界面和功能后,在main()函数里使用Splash窗口。main()函数的代码为,

int main(int argc, char *argv[]){  QApplication a(argc, argv);  FormSplash *splash=new FormSplash();  splash->show();    MainWindow w;  splash->dispInfo("加载模块...");  // 加载模块  // w.load();  splash->dispInfo("加载模块结束");  splash->startTimer(); // 开始计时    w.show();  return a.exec();}

运行效果如图所示,

自定义splash窗口运行效果

标签: #qt程序自启动 #windows窗口属性