【发布时间】:2021-12-23 19:30:29
【问题描述】:
我正在尝试使用 extern 关键字为不同的类使用全局对象,但这在 QT 中不起作用。
基本上我想创建一个通用的 GraphicsScene 对象来在同一场景中绘制矩形,但在不同的类中。这就是为什么我认为全局对象“scene_”在这里会是一个不错的选择。
manwindow.cpp:
QGraphicsScene *scene_ = new QGraphicsScene();
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene_->setSceneRect(-300,-300,600,600);
ui->graphicsView->setScene(scene_);
QGraphicsRectItem *rectItem = new QGraphicsRectItem();
rectItem->setRect(0,0,200,200);
scene_->addItem(rectItem);
}
MainWindow::~MainWindow()
{
delete ui;
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QGraphicsScene>
#include <QMainWindow>
extern QGraphicsScene *scene_;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
这里我想从 mainwindow.h 中检索相同的对象指针 _scene 并向其添加第二个矩形。
交流:
#include "a.h"
#include "mainwindow.h"
#include <QGraphicsRectItem>
A::A()
{
QGraphicsRectItem *rectItem2 = new QGraphicsRectItem();
rectItem2->setRect(0,0,200,200);
scene_->addItem(rectItem2);
}
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
程序在运行时立即崩溃。 (由于关键字实现)
10:17:26: The program has unexpectedly finished.
10:17:26: The process was ended forcefully.
Desktop_Qt_6_2_1_MinGW_64_bit-Debug\debug\test.exe crashed.
我该如何解决这个问题,或者有其他方法可以实现吗?
【问题讨论】:
-
尚未创建。最好是传递它,例如在 A 的构造函数中。但如果你想解决这个问题,你可以这样做: if (!scene_) scene_ = new QGraphicsScene();和 QGraphicsScene *scene_ = nullptr;在 mainwindow.cpp 中
-
这是非常糟糕的设计。不要做。明确说明类和对象的依赖关系。您看到的错误只是这种糟糕设计的结果。
-
我也是这么想的,但不知怎么被卡住了,不知道如何重新设计它。有没有一种方法可以让我修改在类 mainwindow 中实例化的相同场景,并且可以在不使用全局指针的情况下修改其他类中的相同场景。
-
将指针从
MainWindow传递给其他类。