【问题标题】:QT program crashing when using the extern keyword使用 extern 关键字时 QT 程序崩溃
【发布时间】:2021-12-23 19:30:29
【问题描述】:

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

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

ma​​nwindow.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;
}

ma​​inwindow.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);
    }

ma​​in.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 传递给其他类。

标签: c++ qt qt5


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多