Sontung Dang
Sontung Dang

Reputation: 49

Error occurs when show a picture in Qlabel

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdio.h>
#include <iostream>
#include <QDialog>
#include <opencv2\video\video.hpp>
#include <opencv2\opencv.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/flann/miniflann.hpp"
#include <QLabel>
#include <QScrollArea>
#include <QScrollBar>
cv::Mat image1;
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
image1 = cv::imread("D:\\picture.jpg");
QImage       qimage1((uchar*)image1.data,image1.cols,image1.rows,image1.step,QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(qimage1));
}

MainWindow::~MainWindow()
{
delete ui;
}

I have picture with size 720*1280. I want to show this picture in label with size 600*600. However,it only shows a part of the picture. So my question is how to show entire picture without changing the size of picture.

Upvotes: 0

Views: 421

Answers (1)

Shf
Shf

Reputation: 3493

You can use function QPixmap::scaled(), see docs here and examples here

In your case it would be something like this:

ui->label->setPixmap(QPixmap::fromImage(qimage1).scaled(QSize(600,600), Qt::KeepAspectRatio));

It won't affect the image itself, it will construct QPixmap from the image, scale it to fit your 600x600 Qlabel and will keep aspect ration. Hope this will help you. By the way, you don't need yo use OpenCV to just read an image, in Qt QImage class can construct QImage with just QString path_to_image: QImage myImg("D:\\picture.jpg");

EDITED (sorry for the delay):

To add QScrollArea, you have to create it in constructor (let's assume, that in your Mainwindow you have only QLabel and QScrollArea) like this:

// constructor, right after ui->setupUi(this);
QScrollArea *scroll=new QScrollArea(this); // creating instance of QScrollarea with mainwindow as it's parent
scroll->setWidget(ui->label); // sets widget, that you want to have scrollbars
this->setCentralWidget(scroll); // sets scrollarea as centralwidget

Upvotes: 3

Related Questions