c++ - 自定义QGraphicsPixmapItem不显示像素图

标签 c++ qt

我已经制作了一个自定义的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/

相关文章:

c++ - 平面水平旋转

c++ - openGL在不同的显示模式下绘制圆形三角形和正方形

c++ - 有效的无符号到有符号转换避免实现定义的行为

qt - 如何在 Qt qmake 文件(Windows)中使用环境变量?

c++ - 不可能的隐式 move 操作?

c++ - 如何在 QML 中创建自定义基本类型?

reactjs - Qt "passthrough"或 "container"小部件

c++ - 在模板库中输入范围

c++ - QSharedPointer 或 std::shared_ptr 的生命周期

c++ - WIndows 上的 DLL 中未使用 Breakpad 异常处理程序?