c++ - 使用 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.
我该如何解决这个问题,或者有其他方法可以实现吗?
解决方案
为您的设计将工作单身持有公共资源(即场景)。
更好的想法是使用 getter 将场景声明为 MainWindow 的私有成员,或者更好地提供 addItem() 作为公共函数:
void MainWindow::addItem(QGraphicsItem *item)
{
scene->addItem(item);
}
推荐阅读
- scala - 如何在 PySpark 中有条件地加入 2 个 RDD
- amazon-web-services - 调用 terraform 时出现插值错误,而且我不知道如何摆脱它
- security - 如何使用基本身份验证保护 NIFI 站点到站点
- javascript - 使用 JavaScript,我将如何使用数组增加字符串以创建循环?
- android - 寻找 SHA-1 指纹
- amazon-web-services - 为什么 Envoy 使用 AWS 签名代理重复授权标头?
- redis - Redis 服务崩溃并显示“无法打开 RDB 文件 systemdd(在服务器根目录 /etc/cron.d 中)进行保存:权限被拒绝”
- reactjs - 从 parcel v1 -> CRA 切换,如何在开发期间通过重新加载来提供静态 Web 文件
- python - 如何在python中重新连接mongdb?
- php - 输入字段中的日期时间值