QT托盘消息模拟QQ消息通知_播报
2023-05-30 16:10:51
来源:QT教程
(资料图片仅供参考)
使用QQ时,当有消息过来时,托盘的图标一闪一闪的,鼠标悬浮时出现消息通知列表,显示名字和数量,Qt有自带的消息托盘,那没有鼠标悬浮事件,这里通知定时器查找鼠标的坐标,在托盘范围内时显示消息列表,离开托盘范围时隐藏列表,消息列表采用Qt的Model、View加自定义委托实现,代码实现如下:
#ifndef ITEMDEFINE_H#define ITEMDEFINE_H#include #include #include #define PrintTime (QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:"))//托盘消息结构typedef struct STTrayInfo{QString strAvatar{""};//头像QString strName{""};int unReadCount{0};//未读数}TrayInfo;Q_DECLARE_METATYPE(TrayInfo)#endif // ITEMDEFINE_H
#ifndef CITEMDELEGATE_H#define CITEMDELEGATE_H#include #include #include class CItemDelegate : public QStyledItemDelegate{Q_OBJECTpublic:explicit CItemDelegate(QObject *parent = nullptr);~CItemDelegate();//重画函数void paint(QPainter * painter,const QStyleOptionViewItem & option,const QModelIndex & index) const;QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;private:QFont font = QFont("Microsoft YaHei");};#endif // CITEMDELEGATE_H
#include ""#include #include #include #include #include #include #include ""CItemDelegate::CItemDelegate(QObject *parent) :QStyledItemDelegate(parent){(10);}CItemDelegate::~CItemDelegate(){}void CItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{if(()){painter->save();QVariant variant = (Qt::UserRole+1);//根据角色取值TrayInfo data = ();QStyleOptionViewItem viewOption(option);//用来在视图中画一个itemQRectF rect;(());(());(()-1);(()-1);if((QStyle::State_Selected))//选中画背景{painter->setPen(QPen(Qt::blue));painter->setBrush(QColor(229, 241, 255));painter->drawRect(rect);}else if((QStyle::State_MouseOver))//鼠标悬浮画背景{painter->setPen(QPen(Qt::green));painter->setBrush(QColor(189, 193, 217));//bdc1d9painter->drawRect(rect);}// else{//默认状态// painter->setPen(QPen(Qt::gray));// painter->setBrush(Qt::NoBrush);// painter->drawRect(path);// }//画头像QPixmap pix();if(())(":/image/system_");pix = (30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);QRect imageRect = QRect(() + 5, ()+5, 30, 30);painter->drawPixmap(imageRect, pix);//画名字QFontMetrics fontMetrics(font);//如果当前字体下,字符串长度大于100QString fileName = ;if((fileName) >150){fileName = QFontMetrics(font).elidedText(fileName, Qt::ElideRight, 150);}QRect NameRect = QRect(() + 40, ()+10, 150, 18);painter->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing, true);//抗锯齿painter->setPen(QPen(Qt::blue));painter->setFont(font);painter->drawText(NameRect, Qt::AlignLeft, fileName);//画圆QRect circle = QRect(() + 200, ()+5, 30, 20);painter->setBrush(Qt::red);//画填充painter->setPen(QPen(Qt::red));painter->drawRoundedRect(circle, 10, 10, Qt::RelativeSize);//圆角矩形//画统计数字QRect UnReadRect = QRect(() + 200, ()+5, 30, 20);painter->setPen(QPen(Qt::white));painter->setFont(font);painter->drawText(UnReadRect, Qt::AlignCenter, QString("%1").arg());painter->restore();}}QSize CItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const{return QSize(260, 40);}
#ifndef CNOTICELIST_H#define CNOTICELIST_H#include #include #include ""#include ""#include #include namespace Ui {class CNoticeList;}class CNoticeList : public QWidget{Q_OBJECTpublic:explicit CNoticeList(QWidget *parent = nullptr);~CNoticeList();void initView();void initData();void initConnect();void initModelData();void setWidgetHeight();int rowCount();void deleteListItem(const TrayInfo &sessionInfo);void changeListItem(const TrayInfo &sessionInfo);public slots:void slotItemClicked(const QModelIndex &index);void slotIgnoreAll();protected:void mouseReleaseEvent(QMouseEvent *event);private:Ui::CNoticeList *ui;QStandardItemModel *m_model{nullptr};CItemDelegate *m_delegate{nullptr};int m_nMessageTotal{0};QMutex m_MutexNotice;QMap>m_mapMsgid;};#endif // CNOTICELIST_H
#include ""#include "ui_"#include #include #include #include #include CNoticeList::CNoticeList(QWidget *parent) :QWidget(parent),ui(new Ui::CNoticeList){ui->setupUi(this);setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowStaysOnTopHint //不显示菜单栏| Qt::Tool);//不显示任务栏图标initView();initData();initConnect();}CNoticeList::~CNoticeList(){delete ui;}void CNoticeList::initView(){ui->pushButton_ignoreAll->setStyleSheet("QPushButton{""font-family: \"Microsoft YaHei\";""font-size: 12px;""color: blue;}");ui->label_newMesage->setStyleSheet("QLabel{font-family: \"Microsoft YaHei\";font-size: 12px;}");ui->label_count->setStyleSheet("QLabel{font-family: \"Microsoft YaHei\";font-size: 12px;}");ui->listView->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{width:8px;background:rgba(0,0,0,0%);""margin:0px,0px,0px,0px;padding-top:9px;padding-bottom:9px;}"// 留出9px给上面和下面的箭头"QScrollBar::handle:vertical{width:8px;background:rgba(0,0,0,25%);""border-radius:4px;min-height:20;}"// 滚动条两端变成椭圆"QScrollBar::handle:vertical:hover{width:8px;background:rgba(0,0,0,50%);""border-radius:4px;min-height:20;}");// 鼠标放到滚动条上的时候,颜色变深ui->listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);ui->listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);}void CNoticeList::initData(){m_delegate = new CItemDelegate();m_model = new QStandardItemModel();ui->listView->setItemDelegate(m_delegate);ui->listView->setModel(m_model);ui->listView->setSpacing(0);initModelData();}void CNoticeList::initConnect(){connect(ui->listView, &QListView::clicked, this, &CNoticeList::slotItemClicked);connect(ui->pushButton_ignoreAll, &QPushButton::clicked, this, &CNoticeList::slotIgnoreAll);}void CNoticeList::initModelData(){QStringListModel *stringlistModel = new QStringListModel(QColor::colorNames(), this);//获取颜色值QStringList colorList = stringlistModel->stringList();for (int i = 1; i < 7; ++i){QStandardItem *Item = new QStandardItem;TrayInfo itemData; = QString(":/image/%").arg(i); = colorList[i]; = 1;m_nMessageTotal += 1;Item->setData(, Qt::UserRole); // 单一存取 这个用来匹配过滤条件Item->setData(QVariant::fromValue(itemData), Qt::UserRole+1);//整体存取m_model->insertRow(0, Item); //追加Item}setWidgetHeight();}void CNoticeList::setWidgetHeight(){//刷新消息数量if(m_nMessageTotal >0)ui->label_count->setText(QString("%1").arg(m_nMessageTotal));elseui->label_count->setText("");if(m_model->rowCount() < 5){ui->listView->setMinimumHeight(m_model->rowCount() * 40 + 4);ui->listView->setMaximumHeight(m_model->rowCount() * 40 + 4);this->setMinimumHeight(ui->listView->height() + 60);this->setMaximumHeight(ui->listView->height() + 60);}else{ui->listView->setMinimumHeight(204);ui->listView->setMaximumHeight(204);this->setMinimumHeight(264);this->setMaximumHeight(264);}}int CNoticeList::rowCount(){if(nullptr == m_model)return 0;elsem_model->rowCount();}void CNoticeList::mouseReleaseEvent(QMouseEvent *event){if(event->button() == Qt::LeftButton)this->hide();}void CNoticeList::deleteListItem(const TrayInfo &info){for(int i = 0; i < m_model->rowCount(); ++i){QStandardItem *Item = m_model->item(i);QString strName = Item->data(Qt::UserRole).toString();if(0 == ()){QVariant variant = Item->data(Qt::UserRole+1);//根据角色取值TrayInfo data = ();m_nMessageTotal -= ;//总消息数减去这个会话消息数if(m_nMessageTotal < 0)m_nMessageTotal = 0;m_model->removeRow(i);break;}}setWidgetHeight();}void CNoticeList::slotItemClicked(const QModelIndex &index){QMutexLocker locker(&m_MutexNotice);QVariant variant = (Qt::UserRole+1);//根据角色取值TrayInfo data = ();//删除这个itemdeleteListItem(data);//隐藏自己this->hide();}void CNoticeList::slotIgnoreAll(){QMutexLocker locker(&m_MutexNotice);if(m_model->rowCount() >0){m_model->clear();m_nMessageTotal = 0;this->hide();}}
#ifndef CUSTOMSYSTEMTRAY_H#define CUSTOMSYSTEMTRAY_H#include #include #include #include #include #include ""#include ""#include ""class QAction;class QMemu;class QSystemTrayIcon;class QWidget;class QWidgetAction;class QPushButton;class QToolButton;class QLabel;class QHBoxLayout;class QPainter;class QTimer;class CustomSystemTray : public QSystemTrayIcon{Q_OBJECTpublic:explicit CustomSystemTray(QObject *parent = nullptr);void initData();void checkMousePosition();//Qt的托盘没有悬停事件,通过鼠标光标位置来判断悬浮事件void initConnect();public slots:void slotMessageNotice();void slotFlashTimerOut();private:QTimer *m_pMessageNotice{nullptr};//模拟消息通知QTimer *m_pTimerFlash{nullptr};//图标闪烁int m_flashCount{0};CNoticeList *m_noticList{nullptr};};#endif // CUSTOMSYSTEMTRAY_H
#include ""#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include CustomSystemTray::CustomSystemTray(QObject *parent) :QSystemTrayIcon(parent){initData();}void CustomSystemTray::initData(){m_noticList = new CNoticeList();m_pTimerFlash = new QTimer;connect(m_pTimerFlash, &QTimer::timeout, this, &CustomSystemTray::slotFlashTimerOut);m_pTimerFlash->start(500);}void CustomSystemTray::checkMousePosition(){//托盘位置24X40QRect currentRect = geometry();int xMin = ();int xMax = () + ();int yMin = ();int yMax = () + ();int x = QCursor::pos().x();int y = QCursor::pos().y();if(xMin<=x && x<=xMax && yMin<=y && y<=yMax){QRect menuRect;(xMin);(yMin - m_noticList->height());(m_noticList->width());(m_noticList->height());m_noticList->setGeometry(menuRect);if(m_noticList->rowCount() >0)m_noticList->show();elsem_noticList->hide();}else if((nullptr != m_noticList) && (!m_noticList->isHidden())){//如果是显示的消息框,鼠标在显示框范围内不隐藏int pxMin = xMin;int pxMax = xMin + m_noticList->width();int pyMin = yMin - m_noticList->height();int pyMax = yMin;if(pxMin<=x && x<=pxMax && pyMin<=y && y<=pyMax)m_noticList->show();elsem_noticList->hide();}}void CustomSystemTray::initConnect(){// 此处使用定时器模拟消息的发送m_pMessageNotice = new QTimer;connect(m_pMessageNotice, &QTimer::timeout, this, &CustomSystemTray::slotMessageNotice);m_pMessageNotice->start(3000);}void CustomSystemTray::slotMessageNotice(){m_flashCount = 0;if (m_pTimerFlash == nullptr){m_pTimerFlash = new QTimer;connect(m_pTimerFlash, &QTimer::timeout, this, &CustomSystemTray::slotFlashTimerOut);m_pTimerFlash->start(500);}}void CustomSystemTray::slotFlashTimerOut(){if(m_noticList->rowCount() < 1){this->setIcon(QIcon(":/image/"));return;}//qDebug() << "slotFlashTimerOut============m_flashCount=====" << m_flashCount;// 消息通知,使用定时器刷新图标m_flashCount++;checkMousePosition();if (m_flashCount % 2 == 1){this->setIcon(QIcon(":/image/"));}else{this->setIcon(QIcon(":/image/"));}}
运行效果
【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】
点击这里:
关键词:
相关阅读
版权和免责申明
凡注有"环球传媒网"或电头为"环球传媒网"的稿件,均为环球传媒网独家版权所有,未经许可不得转载或镜像;授权转载必须注明来源为"环球传媒网",并保留"环球传媒网"的电头。