在 qt 中缩放图像时滚动条的错误行为 [英] Incorrect behaviour of scroll bars upon zooming an image in qt
问题描述
我正在尝试为我的类似图像查看器的应用程序实现缩放功能.我正在上传这样的图片:
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();
}
像这样放大/缩小:
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)));
}
问题是当我放大/缩小时,滚动条不会改变它们的大小,即无论我放大还是缩小,滚动区域的大小始终等于上传图像的大小.图片说明了我的问题(1 - 不缩放,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?
推荐答案
我已经找到了一个解决方案,但我仍然不知道为什么现在可以使用,但是通过代码创建滚动区域和标签,然后使用 setWidget 方法解决了我的问题..h 文件中的声明:
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;
和.cpp文件中的构造函数:
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);
这篇关于在 qt 中缩放图像时滚动条的错误行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!