我已经制作了一个自定义的QGraphicsPixMap QGraphicsItem,因为我需要具有在有人单击时触发的功能!标题如下所示:
#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
而.cpp可以在这里看到:
#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;
}
当我尝试更新QGraphicsScene(存储在名为“scene”的变量中)中的像素图时,没有出现任何错误,但是未显示PixMap。
这是我在实现自己的QGraphicsPixMap之前运行良好的代码:
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);
}
现在,我正在使用自己的QGraphicsPixMap实现,这是我拥有的代码:
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);
}
问题在于像素图不会加载到QGraphicsScene中。
谢谢你的帮助!
最佳答案
变量的作用域结束时将被销毁,在您的情况下为“NewGPixmap item;”。它是一个局部变量,因此在on_openImage_triggered运行完成后将被删除。如果您希望对象不依赖于变量的生命周期,则必须对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);
}
关于c++ - 自定义QGraphicsPixmapItem不显示像素图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60385376/