hakunami
hakunami

Reputation: 2441

QLabel expands to fit one big iamge, but can't shrink back to fit a small image

I am new to QT, and I want use QT to develope an image manual annotation tool which loads image and allows users annotate them. I look the image viewer demo, and decide to use QLabel to show images, but here is the problem. I want my main window (only for display image, toolbar is floating) can auto-fit with the size of the image loaded. I change the code of image viwer to this:

ImageViewer::ImageViewer()
{
    imageLabel = new QLabel;
    imageLabel->setBackgroundRole(QPalette::Base);
    imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    imageLabel->setScaledContents(false);
    setCentralWidget(imageLabel);

    createActions();
    createMenus();

    setWindowTitle(tr("Image Viewer"));
    resize(sizeHint());
}

void ImageViewer::open()
{

    QString fileName = QFileDialog::getOpenFileName(this,
                                    tr("Open File"), QDir::currentPath());
    if (!fileName.isEmpty()) {
        QImage image(fileName);
        if (image.isNull()) {
            QMessageBox::information(this, tr("Image Viewer"),
                                     tr("Cannot load %1.").arg(fileName));
            return;
        }

        imageLabel->setPixmap(QPixmap::fromImage(image));
        imageLabel->adjustSize();

    }
}

With this code, the main window(QLabel) can expand to fit a large image, but when I load a small size image, it can't shrink back to the size of this image. What's wrong happens here?

Thank you very much.

Upvotes: 1

Views: 1241

Answers (4)

bootcap
bootcap

Reputation: 1

Just try the following code:

layout.setSizeConstraint(QLayout::SetFixedSize);

Upvotes: 0

mahesh
mahesh

Reputation: 1098

For someone still looking for an answer, as pointed out here, you need to set the minimum size property:

 imageLabel->setMinimumSize(1, 1);

Upvotes: 1

Hafnernuss
Hafnernuss

Reputation: 2817

For the sake of completeness, setting the size Policy of the label to "Maximum" is the fastest way.

Upvotes: 0

MrFox
MrFox

Reputation: 1254

I believe that your problem is the size policy you're setting, try QSizePolicy::Minimum instead of QSizePolicy::Expanding.

Upvotes: 0

Related Questions