回到顶部效果 上一篇博客:Qt实现右下角消息通知队列的通知是会定时关闭销毁的,最多同时显示5个通知。但有些情况下,不想前面的通知被销毁,要求保留可以一直浏览的话,就不能用了,所以改写了下,用这篇博客总结下。点击提示1按钮,加入通知信息到数据队列中,并显示摇晃动画,添加到QScrollArea滚动区域中,方便超出5个通知时可以滚动浏览;可以删除,删除也添加向右移动隐藏动画。 下载地址 https:github。comconfidentFengQtAppProjec关键代码 NotifyWidget。cppNotifyManager::NotifyManager(QWidgetparent):QWidget(parent){thissetFixedSize(320,600);thissetWindowFlags(Qt::FramelessWindowHintQt::WindowStaysOnTopHint);thissetObjectName(NotifyManager);创建一个子窗口,这个子窗口交给滚动区域QWidgetpSubWidgetnewQWidget(this);创建滚动区域mpScrollAreanewQScrollArea(this);mpScrollAreasetFixedSize(width(),NOTIFYHEIGHT);mpScrollAreasetWidgetResizable(true);决定着滚动区域是否应调整子widget的大小mpScrollAreaverticalScrollBar()setSingleStep(NOTIFYHEIGHT3);设置步长,每次滚动滚轮只上移或下移一个itemmpScrollAreasetWidget(pSubWidget);子widget可以使用QScrollArea::setWidget(QWidgetwidget)来指定mpScrollAreamove(QPoint(0,height()NOTIFYHEIGHT));给子窗口设置一个垂直布局,方便动态添加通知mpLayoutSubnewQVBoxLayout(pSubWidget);mpLayoutSubsetSpacing(NOTIFYSPACE);mpLayoutSubsetContentsMargins(0,0,0,0);mpLayoutSubaddStretch();初始化队列的通知数目界面mpNotifyCntWidgetnewNotifyCountWidget(this);mpNotifyCntWidgethide();显示队列的通知数目的定时器mpTimerCntnewQTimer(this);mpTimerCntsetSingleShot(true);mpTimerCntsetInterval(3000);connect(mpTimerCnt,QTimer::timeout,〔〕{mpNotifyCntWidgethide();mpNotifyCntWidgetisStartAnim(false);结束动画});队列定时器mpTimerQueuenewQTimer(this);mpTimerQueuesetInterval(500);mpTimerQueuestart();connect(mpTimerQueue,QTimer::timeout,〔〕{showQueueNotify();});}通知入队voidNotifyManager::notifyEnqueue(constQStringtitle,constQStringbody,constQVariantMapdata){将标题栏和内容数据添加到队列中QVariantMaptmpdata;tmp。insert(title,title);tmp。insert(body,body);tmp。insert(icon,mdefaultIcon);mdataQueue。enqueue(tmp);}显示队列中的通知voidNotifyManager::showQueueNotify(){mpTimerQueuestop();如果通知数目超出限制,则显示通知当前数目界面if(mnotifyCountNOTIFYMAXCOUNTmdataQueue。isEmpty()){mpTimerQueuestart();return;}创建并显示新的通知NotifyWidgetnotifyWidgetnewNotifyWidget(this);将管理员自身传给notifyWidget的mmanagernotifyWidgetsetData(mdataQueue。dequeue());设置数据队列的第一个数据(dequeue,删除队列第一个元素,并返回这个元素)mpLayoutSubinsertWidget(0,notifyWidget);mnotifyCount;显示新的通知时,摇晃动画animationShake(notifyWidget,800,〔〕(){mpTimerQueuestart();});通知销毁之后触发下面槽函数connect(notifyWidget,QObject::destroyed,this,〔this〕(){mnotifyCount;更新滚动区域的高度updateAreaHeight();});更新滚动区域的高度updateAreaHeight();}更新滚动区域的高度voidNotifyManager::updateAreaHeight(){布局最前面插入通知if(mnotifyCountVIEWITEM){mpScrollAreamove(QPoint(0,height()NOTIFYHEIGHTmnotifyCount));mpScrollAreasetFixedHeight(NOTIFYHEIGHTmnotifyCount);}else{显示队列的通知数目showQueueCount();mpScrollAreasetFixedHeight(NOTIFYHEIGHT(VIEWITEM1)10);}} 点击领取Qt学习资料视频教程链接