I have made a custom QGraphicsPixMap QGraphicsItem as I need to have functions that trigger when someone clicks on it! The header for this is seen below:
#ifndef NEWGPIXMAP_H
#define NEWGPIXMAP_H
#include <QObject>
#include <QGraphicsPixmapItem>
#include <QGraphicsSceneMouseEvent>
class NewGPixmap : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
NewGPixmap();
void mousePressEvent(QGraphicsSceneMouseEvent *event);
// void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
// void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
};
#endif // NEWGPIXMAP_H
And the .cpp for this can be seen here:
#include "newgpixmap.h"
#include <iostream>
#include <QPointF>
NewGPixmap::NewGPixmap()
{
}
void NewGPixmap::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QPointF pos = event->pos();
int x = pos.x();
int y = pos.y();
std::cout<<x<<" "<<y<<std::endl;
}
When I try and update the pixmap in the QGraphicsScene (stored in a variable called "scene") I get no errors however the PixMap isn't displayed.
This is the code I used prior to implementing my own QGraphicsPixMap which worked fine:
void MainWindow::on_openImage_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose File"));
QImage image(fileName);
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->clear();
scene->addItem(item);
}
And now that I am using my own QGraphicsPixMap implementation, this is what code I have:
void MainWindow::on_openImage_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose File"));
QImage image(fileName);
NewGPixmap item;
item.setPixmap(QPixmap::fromImage(image));
scene->clear();
scene->addItem(&item);
}
The problem is that the pixmap wont load into the QGraphicsScene.
Thanks for your help!
Variables are destroyed when their scope ends, in your case "NewGPixmap item;" it is a local variable so it will be deleted when finished running on_openImage_triggered. If you want the object to not depend on the life cycle of the variable then you must use a pointer like your example with QGraphicsPixmapItem:
void MainWindow::on_openImage_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose File"));
QImage image(fileName);
NewGPixmap *item = new NewGPixmap;
item->setPixmap(QPixmap::fromImage(image));
scene->clear();
scene->addItem(item);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.