使用extern关键字时QT程序崩溃



我试图使用extern关键字为不同的类使用全局对象,但这在QT中不起作用。

基本上,我想创建一个通用的GraphicsScene对象,在同一个场景中绘制不同类的矩形。这就是为什么我认为一个全局对象";场景_;在这里会是个不错的选择。

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;
}

主窗口.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,并添加第二个矩形

A.c

#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-Debugdebugtest.exe crashed.

我该如何解决此问题,或者是否有其他方法来实现此问题?

对于您的设计,将单独使用公共资源(即场景(。

更好的想法是用getter将场景声明为MainWindow的私有成员,或者更好地将addItem((提供为公共函数:

void MainWindow::addItem(QGraphicsItem *item)
{
scene->addItem(item);
}

最新更新