Qt 从 QGridLayout 的自定义对象访问变量

Qt access variable from custom object from QGridLayout

我已经创建了自己的 QGraphicsView,因此我可以使用 mousePressEvent 方法。然后我将 "new" 小部件添加到 MainWindow。现在我需要从那个对象访问一个场景,但我无法访问它。

privqgraphicsview.cpp

#include "privqgraphicsview.h"
#include <QPointF>

MyQGraphicsView::MyQGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    scene = new QGraphicsScene();
    this->setSceneRect(-320, -290, 660, 580);
    this->setScene(scene);
    this->setRenderHint(QPainter::Antialiasing);
}

privqgraphicsview.h

#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
#include <QMouseEvent>

   class MyQGraphicsView : public QGraphicsView
   {
       Q_OBJECT
   public:
       explicit MyQGraphicsView(QWidget *parent = 0);
       QGraphicsScene * scene;

   public slots:
       void mousePressEvent(QMouseEvent * e);

   };

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "privqgraphicsview.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // gridLayout is defined in mainwindow.h
    gridLayout = new QGridLayout(ui->centralWidget);
    gridLayout->addWidget( new MyQGraphicsView() );
}

MainWindow::~MainWindow()
{
    delete ui;
}

现在,我有 MainWindow 中的按钮,我想在点击事件中连接 MyQGraphicsView 中来自 gridLayoutscene 中的点。我试过这样的事情:

void MainWindow::on_connectPointsPB_clicked()
{
    QLayoutItem *myView = gridLayout->itemAt(0);
    // trying to draw a simple line, code below does not check anything, I am aware of it
    dynamic_cast<MyQGraphicsView *>(myView)->scene->addLine(10,10,50,50, QPen(Qt::red, 3));
}

并且在单击按钮后关闭(崩溃)应用程序。

您不应投射 QLayoutItem,而应投射 QLayoutItem::widget to your MyQGraphicsView. If you checked the outcome of dynamic_cast<MyQGraphicsView *>(myView), you would have noticed that it returns NULL. Note that it may be useful to use qobject_cast 而不是 dynamic_cast,这不需要 RTTI 支持。

更简洁的解决方案 是将您的 MyQGraphicsView 对象存储为 MainWindow 的成员,因此您不需要转换任何内容。