QGraphicsScene中未显示图像

Image is not shown in QGraphicsScene

本文关键字:显示图 图像 显示 QGraphicsScene      更新时间:2023-10-16

描述

我写了以下Qt代码。并生成适用于Windows的可执行文件(*.exe(。但QGraphicsScene中未显示图像(JPG(。我已经检查了图像的路径是否正确。在下面的代码中,MyQGraphicsScene派生类继承了QGraphicsSene类。

我在macOS中编译了相同的代码。然后,macOS的可执行文件(ELF(正确运行。图像文件显示在其组件中。我觉得源代码是一样的。但结果因环境而异。

开发环境

  • Windows 10
  • Qt版本:5.7.0
  • C++编译器:Microsoft Visual C++14.0版(MSVC2015(

源代码

    #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsRectItem>
#include <QMessageBox>
#include <QIcon>
#include "TrainingData.h"
#include "trainingDataMaker.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QGraphicsItem *curGItem;
    QListWidgetItem *listItem;
    ui->setupUi(this);
    scene = new MyQGraphicsScene(QRectF(0, 0, 400, 400));
    ui->graphicsView->setScene(scene);
    listItem = new QListWidgetItem();
    listItem->setIcon(QIcon("data/000001.jpg"));
    ui->imgListWidget->addItem(listItem);
    listItem = new QListWidgetItem();
    listItem->setIcon(QIcon("data/000276.jpg"));
    ui->imgListWidget->addItem(listItem);
    ui->imgListWidget->setIconSize(QSize(300,100));

    QPixmap pixmap;
    QImage img("data/000001.jpg");
    QTransform transForm;
    pixmap = QPixmap::fromImage(img);
    QGraphicsPixmapItem *imgPixmap = new QGraphicsPixmapItem(pixmap);
    transForm = QTransform();
    transForm.scale(0.1, 0.1);
    imgPixmap->setTransform(transForm);
    scene->addItem(imgPixmap);
    //connect(scene, SIGNAL(changed(const QList<QRectF> &)), imgPixmap, SLOT(chgSize(const QList<QRectF> &)));
}

我在macOS中编译了相同的代码。然后,macOS的可执行文件(ELF(运行正确。图像文件显示在其组件中。我觉得很尴尬那个源代码是一样的。但结果因环境而异。

由于它在MacOS/X下工作,但在Windows下不工作,一个可能的解释是这是一个分发/环境问题。特别是,也许您的程序在Windows下找不到Qt的图像格式插件(例如qjpeg4.dll或qjpeg5.dll(,这就是为什么图像没有显示的原因。

为了测试这一理论,你可以将qjpeg*.dll插件文件复制到与你的.exe文件相同的文件夹中,然后重新运行你的程序,看看这是否会让它表现得更好。或者,如果你不想使用图像格式插件,你可以将.jpg文件转换为Qt支持的另一种文件格式,如BMP或PNG,然后使用它。

因此,如果应用程序是从IDE启动的,则此问题的原因是我对当前目录的误解。当前目录是下图中的(a(。

之前的目录结构

[Output directory is specified in build configuration] - (a)
  |- debug - (b)
  |    |- test.exe // executable file of this application
  |    |- data
  |        |-000001.jpg
  |- release

所以,我应该已经定位了"数据"目录,包括目录(a(中的图像文件,如下图所示。我对IDE的这种规格感到奇怪。当然,在应用程序直接启动的情况下,当前目录与exe文件的目录相同(双击exe文件(。

之后的目录结构

[Output directory is specified in build configuration] - (a)
  |- debug - (b)
  |    |- test.exe // executable file of this application
  |- release
  |- data
      |-000001.jpg