图像不显示在QGraphicsScene

问题描述:

描述

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

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

发展环境

  • 的Windows 10
  • 的Qt版本:5.7.0
  • C++编译器:微软的Visual C++ Ver.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> &))); 

} 

因此,这个问题的原因是我的误解当前目录在应用程序从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的规范很奇怪。当然,当应用程序直接启动时(Doublu点击exe文件),当前目录与exe文件是相同的。

后的目录结构

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

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

由于它在MacOS/X下工作,但不能在Windows下工作,有一种可能的解释是它是一个分布/环境问题。尤其是,您的程序可能无法在Windows下找到Qt的imageformat插件(例如qjpeg4.dll或qjpeg5.dll),这就是为什么图像没有显示出来。

要测试该理论,可以将qjpeg * .dll插件文件复制到与.exe文件相同的文件夹中,然后重新运行程序并查看它是否使其表现更好。或者,如果您不想混淆图像格式插件,则可以将.jpg文件转换为另一种文件格式,Qt包含原生(即非基于插件的)支持,例如BMP或PNG,并使用该格式代替。

+0

感谢您的宝贵意见。我无法在Qt安装目录下找到qjpeg [4 | 5 [.dll]。但我发现qjpeg.dll。 – kuni255

+0

所以我复制这个qjpeg.dll与exe文件相同的目录。并运行应用程序。但图像文件仍然没有显示。 – kuni255

+0

此外,我将图像文件格式JPG转换为PNG。但图像文件没有显示。 – kuni255