kuni255 kuni255 - 2 months ago 15
C++ Question

Image is not shown in QGraphicsScene

Description




I wrote following Qt code. And Make executable file for Windows (*.exe). But Image (JPG) is not shown in QGraphicsScene. And I had already checked whether the path to image is correct. In following code, MyQGraphicsScene is derived class inherits QGraphicsScene class.



I compiled same code in macOS. Then, Executable file (ELF) for macOS ran correctly. Image file was shown in its component. I feel starange that source code is same. But the result is different by environment.


Development environment




  • Windows 10

  • Qt version : 5.7.0

  • C++ Compiler : Microsoft Visual C++ Ver.14.0 (MSVC2015)



Source code



#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> &)));

}

Answer

As result, Cause of this issue is my misunderstanding of current directory in case that the application is launched from IDE. Current directory is (a) in following diagram.

Directory structure before

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

Therefore, I should have located "data" directory includes image files in directory (a) as following diagram. I'm feeling strange this specification of IDE. Of course, Current directory is same diretory of exe file in case that application launch directly(Doublu-clicking exe file) .

Directory structure after

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