Reputation: 630
I'm trying to implement zooming feature to my image-viewer-like appliction. I'm uploading an image like so:
void MeasuresWidget::on_actionOpen_triggered()
{
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;
}
ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}
scaleFactor = 1.0;
// ui->imageLabel->adjustSize();
}
And zoom in/out like so:
void MeasuresWidget::on_actionZoom_in_triggered()
{
scaleImage(1.25);
}
void MeasuresWidget::on_actionZoom_out_triggered()
{
scaleImage(0.8);
}
void MeasuresWidget::scaleImage(double factor)
{
Q_ASSERT(ui->imageLabel->pixmap());
scaleFactor *= factor;
ui->imageLabel->resize(scaleFactor * ui->imageLabel->pixmap()->size());
adjustScrollBar(ui->scrollArea->horizontalScrollBar(), factor);
adjustScrollBar(ui->scrollArea->verticalScrollBar(), factor);
}
void MeasuresWidget::adjustScrollBar(QScrollBar *scrollBar, double factor)
{
scrollBar->setValue(int(factor * scrollBar->value()
+ ((factor - 1) * scrollBar->pageStep()/2)));
}
The problem is that when i zoom in/out, scroll bars do not change their size, i.e. the size of scroll area is always equal to the size of uploaded image, no matter whether i zoom in or out. Pictures illustrate my problem (1 - no zoom, 2 - zoomed out once) Any idea on possible solution?
Upvotes: 1
Views: 369
Reputation: 630
I've come to a solution and i still don't know why is this working now, but creating scroll area and label through code and then using setWidget method solved my problem. Declaration in .h file:
QLabel *imageLabel;
QScrollArea *scrollArea;
And constructor in .cpp file:
imageLabel = new QLabel;
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);
scrollArea = new QScrollArea;
ui->verticalLayout_4->addWidget(scrollArea);
scrollArea->setWidget(imageLabel);
Upvotes: 1