如何在其他文件中使用主文件的场景对象

how to use scene object of main file in other file?

本文关键字:主文件 对象 其他 文件      更新时间:2023-10-16

我试图使用Qt和Qgraphicsview制作tictactoe游戏,但是当我在mousePressEvent中使用Graphicstextitem绘制x时,X没有出现。 如何解决?

我认为问题是文本项的场景与主文件的场景不同,但我不知道如何解决这个问题。

主.cpp:

int main(int argc, char *argv[])
 {
   QApplication a(argc, argv);
      Game *gm = new Game;
     Game *rect1=new Game;
  gm->scenc->setSceneRect(0,0,800,600);
  rect1->setRect(160,100,150,150);
  gm->scenc->addItem(rect1);
  gm->view->setScene(gm->scenc);
  gm->view->show();
  return a.exec();
 }

在游戏中.cpp:

#include <game.h>
 Game::Game()
 {
  scenc= new QGraphicsScene;
  view = new QGraphicsView;
  text= new QGraphicsTextItem;
}
 void Game::mousePressEvent(QGraphicsSceneMouseEvent *event)
 {
    if (event->buttons() == Qt::LeftButton )
     { 
                 text->setPlainText("X");
                 text->setFont(QFont("Tahoma",24));
                 text->setPos((160+160+120)/2,140);
                 scenc->addItem(text);

     } 
   }

在游戏中:

 class Game : public QObject , public QGraphicsRectItem
{
    Q_OBJECT
    public:
     Game();
     QGraphicsScene *scenc;
     QGraphicsView *view;
     QGraphicsTextItem *text;
     void mousePressEvent(QGraphicsSceneMouseEvent *event);


       };

下面的示例说明了如何以正确的方式执行此操作。首先,您必须注意,Game::mousePressEvent不会覆盖任何虚函数。使用覆盖关键字并删除虚拟关键字以确保虚拟函数被覆盖是一个好习惯。

游戏不是从QGraphicsScene派生的,因此没有mousePressEvent成员。

请尝试以下示例应用。

我的场景

#pragma once
#include <QWidget>
#include <QDebug>
#include <QHBoxLayout>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QGraphicsSceneMouseEvent>
class MyScene : public QGraphicsScene {
    Q_OBJECT
public:
    MyScene(QWidget* parent = nullptr) : QGraphicsScene(parent) {
        setSceneRect(0, 0, 800, 600);       
    }
    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* mouseEvent) override {
        if (mouseEvent->buttons() == Qt::LeftButton)
        {
            auto text = new QGraphicsTextItem;
            addItem(text);
            text->setPlainText("X");
            text->setPos(mouseEvent->scenePos());
        }
    }
private:
    QGraphicsView* mView;
    QGraphicsTextItem* mText;
};

主.cpp

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include "MyScene.h"
int main(int argc, char* argv[])
{
    QApplication a(argc, argv);
    auto scene = new MyScene;
    auto view = new QGraphicsView;
    view->setScene(scene);
    view->show();
    return a.exec();
}