打地鼠游戏(6)

对于记分控件,因为是在点击到老鼠图元的情况下才会触发记分,但是记分控件是mainwindow的属性,图元怎么通知到mainwindow?

mainwindow中能够访问的是view容器,容器包含场景,场景包含图元,怎么实现图元通知到mainwindow——单例模式。

设计思路:

首先创建一个随处可以访问的一个对象(单例)然后这个对象可以发送信号(继承自QObject),在单击到老鼠时,触发发送信号,然后再在mainwindow中去捕获这个信号,更新记分控件。

1、首先创建单例:

 1 #ifndef HANDLE_H
 2 #define HANDLE_H
 3 
 4 #include <QObject>
 5 
 6 class handle : public QObject
 7 {
 8     Q_OBJECT
 9 public:
10     static handle* getinstence();
11     void addscore();
12     ~handle(){
13         if(pt_handle != NULL){
14             delete pt_handle;
15         }
16     }
17 private:
18     explicit handle(QObject *parent = nullptr);
19     static handle* pt_handle;
20 
21 signals:
22     void send_sigal();  //自定义信号,只需要声明,不需要定义
23 
24 };
25 
26 #endif // HANDLE_H
 1 #include "handle.h"
 2 
 3 handle::handle(QObject *parent) : QObject(parent)
 4 {
 5 
 6 }
 7 
 8 handle* handle::pt_handle = NULL;
 9 
10 handle* handle::getinstence(){
11     if(pt_handle == NULL){
12         pt_handle = new handle();
13     }
14 }
15 
16 void handle::addscore(){
17     emit send_sigal();  //发送自定义信号
18 }

当点击到老鼠,调用发送信号的函数——addscore()

 1 //------------------------------------myitem.cpp
 2 void myitem::mousePressEvent(QGraphicsSceneMouseEvent *event){
 3     //判断当前是否是老鼠
 4     if(this->ismouse()){
 5         qDebug()<<"打到老鼠";
 6         handle* pt = handle::getinstence();
 7         pt->addscore();
 8     }else{
 9         qDebug()<<"未打到老鼠";
10     }
11 }

在mainwindow中去绑定,该信号,并定义槽函数

 1 #ifndef MAINWINDOW_H
 2 #define MAINWINDOW_H
 3 
 4 #include <QMainWindow>
 5 
 6 #include "myscene.h"
 7 
 8 #include "handle.h"
 9 
10 namespace Ui {
11 class MainWindow;
12 }
13 
14 class MainWindow : public QMainWindow
15 {
16     Q_OBJECT
17 
18 public:
19     explicit MainWindow(QWidget *parent = nullptr);
20     ~MainWindow();
21 
22     virtual void closeEvent(QCloseEvent *event);
23 
24 private:
25     Ui::MainWindow *ui;
26     MyScene * sc;
27 private slots:
28     void updatescore(); //更新显示记分器
29 private:
30     int score;      //记分
31     handle* pt;
32 
33 };
34 
35 #endif // MAINWINDOW_H
 1 MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
 2 {
 3     ui->setupUi(this);
 4     //将场景在容器中进行显式
 5     this->sc = new MyScene();
 6     ui->graphicsView->setScene(this->sc);
 7 
 8     //控件绑定
 9     connect(this->ui->btn_begin,SIGNAL(clicked()),this->sc,SLOT(start_game()));
10     connect(this->ui->btn_hold,SIGNAL(clicked()),this->sc,SLOT(hold_game()));
11     connect(this->ui->btn_end,SIGNAL(clicked()),this->sc,SLOT(end_game()));
12 
13     this->score = 0;
14     this->pt = handle::getinstence();
15     connect(this->pt,SIGNAL(send_sigal()),this,SLOT(updatescore()));
16 }
17 
18 void MainWindow::updatescore(){
19     this->score += 10;
20     this->ui->lcdnum->display(this->score);
21 
22 }

猜你喜欢

转载自www.cnblogs.com/data1213/p/10852233.html