Qt-桌面宠物
目录
一,演示(部分功能)
二,开发环境准备
三,部分代码实现
1.创建基础窗口
2.实现宠物动画
3.添加交互功能
4.系统托盘集成
5.行为模式实现
6.状态管理系统
7.资源打包部署
四,接受定制
一,演示(部分功能)
二,开发环境准备
安装Qt Creator和Qt框架(建议5.14或更新版本) 配置C++编译环境(MSVC/MinGW) 准备素材资源(PNG序列帧/透明背景素材)
三,部分代码实现
1.创建基础窗口
QWidget *petWindow = new QWidget(nullptr, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
petWindow->setAttribute(Qt::WA_TranslucentBackground);
petWindow->setFixedSize(320, 489);
2.实现宠物动画
使用QMovie加载GIF动画或QLabel显示帧序列:
QLabel *petLabel = new QLabel(petWindow);
QMovie *petMovie = new QMovie(":/animations/idle.gif");
petLabel->setMovie(petMovie);
petMovie->start();
3.添加交互功能
实现鼠标拖拽和点击事件:
void PetWidget::mousePressEvent(QMouseEvent *event) {if (event->button() == Qt::LeftButton) {m_dragPosition = event->globalPos() - frameGeometry().topLeft();event->accept();}
}void PetWidget::mouseMoveEvent(QMouseEvent *event) {if (event->buttons() & Qt::LeftButton) {move(event->globalPos() - m_dragPosition);event->accept();}
}
4.系统托盘集成
创建右键菜单和托盘图标:
QSystemTrayIcon *trayIcon = new QSystemTrayIcon(QIcon(":/icon.png"), this);
QMenu *trayMenu = new QMenu();
trayMenu->addAction("退出", qApp, &QCoreApplication::quit);
trayIcon->setContextMenu(trayMenu);
trayIcon->show();
5.行为模式实现
添加随机移动和边缘检测:
void PetWidget::startRandomMovement() {QTimer *moveTimer = new QTimer(this);connect(moveTimer, &QTimer::timeout, [this]() {QPoint newPos = pos() + QPoint(qrand() % 10 - 5, qrand() % 10 - 5);newPos = ensureInScreenBounds(newPos);move(newPos);});moveTimer->start(1000);
}
6.状态管理系统
实现不同行为状态切换:
enum PetState { IDLE, WALK, SLEEP, EAT };
void setPetState(PetState state) {currentState = state;updateAnimation();updateBehavior();
}
7.资源打包部署
使用Qt资源系统(.qrc文件)打包素材 发布时通过windeployqt工具收集依赖项 可考虑使用打包软件制作安装包
四,接受定制
可以定制角色,实现对应功能