ProgAndPlay
ProgAndPlay

Reputation: 277

Qt/C++ image does not appear on screen

Here is the code for the MainWindow constructor where I tried to make an image (000.jpg) appear on the screen. What could be wrong? Are there alternative ways of showing an image on screen from a file? PS: The image file is in the same directory where the .cpp project files are.

 MainWindow::MainWindow()
 {
     QWidget *widget = new QWidget;
     setCentralWidget(widget);

     QWidget *topFiller = new QWidget;
     topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

     QWidget *bottomFiller = new QWidget;
     bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

     QVBoxLayout *layout = new QVBoxLayout;
     layout->setMargin(5);
     layout->addWidget(topFiller);

     QImage myImg("000.jpg");
     myImageFile = myImg;
     imageLabel = new QLabel();
     imageLabel->setBackgroundRole(QPalette::Base);
     imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
     imageLabel->setScaledContents(true);
     imageLabel->setPixmap(QPixmap::fromImage(myImageFile));
     layout->addWidget(imageLabel);

     layout->addWidget(bottomFiller);
     widget->setLayout(layout);

     createActions();
     createMenus();

     setWindowTitle(tr("Image App"));
     setMinimumSize(160, 160);
     resize(480, 320);
 }

Upvotes: 1

Views: 379

Answers (1)

Mohammad Kanan
Mohammad Kanan

Reputation: 4582

The Problem comes about because of ignore policy, the label seems failing to expand the layout (After or because topFiller and bottomFiller expand) :

  imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);

try instead a normal policy by removing setSizePolicy(), or use Expanding:

imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

Also its good to set the QLabel setScaledContents so that the image will resize when you manually resize the view:

imageLabel->setScaledContents(true);

Upvotes: 2

Related Questions