解释如何使用指针



对不起,我使用谷歌翻译。我正在探索QGraphicsItem是如何工作的。但我不明白数据是如何通过指向场景的指针传输的。这是一个代码

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmyscene.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QMyScene(this);
ui->graphicsView->setScene(scene);
scene->setSceneRect(0,0,800,600);
}
MainWindow::~MainWindow()
{
delete ui;
}

qmyscene.cpp

#include "qmyscene.h"
#include "qpixitem.h"
#include <qdebug.h>
QMyScene::QMyScene(QObject *parent) : QGraphicsScene(parent)
{
QPixItem *pix1 = new QPixItem (this,100,100);
QPixItem *pix2 = new QPixItem (this,50,50);
}
QMyScene::~QMyScene()
{
}

qpixitem.cpp

#include "qpixitem.h"
#include <QMessageBox>
QPixItem::QPixItem (QGraphicsScene *MyScene,int x,int y): QGraphicsPixmapItem()
{
QPixmap  pic (":/Items/OutLet.png");
this->setPixmap(pic);
this->setPos(x, y);
this->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges);
qDebug() << "create";
QGraphicsLineItem* line = MyScene->addLine(QLineF(40, 40, 80, 80));
MyScene->addItem(this);
}
QVariant QPixItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange)
{
QPointF newPos = value.toPointF();
int p1 = newPos.x();
int p2 = newPos.y();
MyScene->addLine(QLineF(40,40,p1, p2)); //error
//this->line->setLine(QLineF(40,40,p1, p2)); //error
qDebug() << "Scene::move";
}
return QGraphicsItem::itemChange(change, value);
}

qmyscene.h

#ifndef QMYSCENE_H
#define QMYSCENE_H
#include <QGraphicsScene>
#include <QDebug>
class QMyScene: public QGraphicsScene
{
Q_OBJECT
public:
explicit QMyScene(QObject *parent = 0);
~QMyScene();
private:
};
#endif // QMYSCENE_H

qpixitem.h

#ifndef QPIXITEM_H
#define QPIXITEM_H
#include <QGraphicsItem>
#include "QGraphicsScene"
#include "mainwindow.h"
#include <QGraphicsPixmapItem>
class QPixItem: public QGraphicsPixmapItem
{
public:
QPixItem (QGraphicsScene *MyScene,int x,int y);
QGraphicsScene *MyScene;
int x,y;
private:
QGraphicsLineItem* line;
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
};
#endif // QPIXITEM_H

//error-这些行导致错误(由于内存访问而关闭程序(,我确信这是由于指针使用不当造成的。如何在这样的代码中正确使用它们?

您似乎从未分配过this->line

你的意思是:

this->line = MyScene->addLine(QLineF(40, 40, 80, 80));

代替

QGraphicsLineItem* line = MyScene->addLine(QLineF(40, 40, 80, 80));

相关内容

  • 没有找到相关文章

最新更新