目錄
一,演示(部分功能)
二,開發環境準備
三,部分代碼實現
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工具收集依賴項 可考慮使用打包軟件制作安裝包
四,接受定制
可以定制角色,實現對應功能