如何在其他文件中使用主文件的场景对象
how to use scene object of main file in other file?
我试图使用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();
}
相关文章:
- 如何使用命令提示符、记事本和 MinGW 使用主文件、头文件和实现文件编译C++程序?
- CLANG 格式不对主文件进行排序
- C++警告:编译指示在主文件中一次
- 如何在其他文件中使用主文件的场景对象
- 尝试在 ahead 文件上使用结构,并将其包含在主文件和类文件中
- 将函数及其实现移动到与主文件不同的文件(.hpp 和 .cpp)时,性能会受到很大影响
- 无论如何,在我的主文件之外传递 argc、argv .cpp
- 编译几个源文件(主文件和头文件)并在ROOT CINT中链接它们
- 如何在同一个主文件中转发声明类似模板函数的模板类
- Xcode 不会检测包含文件中的主文件中包含的文件
- 带有C++主文件的 FreeRTOS
- 如何创建一个只有主文件和模板头(C++)的makefile
- 文件移动 - 操作系统如何知道是更新主文件表还是复制和删除
- 无法从头文件C++从主文件访问函数
- 在 Mingw 主文件夹之外构建和编译文件
- C++主文件不显示所有内容
- 定义函数后主文件出错? "undefined reference to 'sequence::sequence()'"
- 在我的主文件中全局创建c++类实例
- 如何将主文件分成三个文件:头文件、客户端和实现
- NDK主文件夹中的目录与NDK版本有什么关系?