首页 > 解决方案 > 使用 extern 关键字时 QT 程序崩溃

问题描述

我正在尝试使用 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;
}

主窗口.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);
    }

主.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.

我该如何解决这个问题,或者有其他方法可以实现吗?

标签: c++qtqt5

解决方案


为您的设计将工作单身持有公共资源(即场景)。

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

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

推荐阅读