且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

QLabel:缩放图像以放大和降低图片质量

更新时间:2023-02-14 07:36:52

您没有显示相关代码,您显示的内容很好.据我所知,您正在尝试调整标签中显示的像素图和标签本身的大小.你应该做一个或另一个,而不是两者都做.调整标签大小最简单,让滚动区域发挥其魔力.这让整个事情变得微不足道.

You're not showing the relevant code, what you do show is fine. From what I can glean you're trying to resize both the pixmap shown in the label, and the label itself. You should be doing one or the other, not both. It's simplest to resize the label, and let the scroll area work its magic. This makes the whole affair trivial.

下面的代码,没有修复它所需的修改,是你应该在你的问题中发布的内容.

The code below, sans modifications needed to fix it, is what you should have posted in your question.

// https://github.com/KubaO/***n/tree/master/questions/image-view-scale-31619246
#include <QtWidgets>
#include <QtNetwork>

class FragTreeViewer : public QWidget {
   QGridLayout m_layout{this};
   QScrollArea m_area;
   QLabel m_imageLabel, m_scaleLabel;
   QPushButton m_zoomOut{"Zoom Out"}, m_zoomIn{"Zoom In"};
   double m_scaleFactor = 1.0;
public:
   void setImage(const QImage & img) {
      m_scaleFactor = 1.0;
      m_imageLabel.setPixmap(QPixmap::fromImage(img));
      scaleImage(1.0);
   }
   FragTreeViewer() {
      m_layout.addWidget(&m_area, 0, 0, 1, 3);
      m_layout.addWidget(&m_zoomOut, 1, 0);
      m_layout.addWidget(&m_scaleLabel, 1, 1);
      m_layout.addWidget(&m_zoomIn, 1, 2);
      m_area.setWidget(&m_imageLabel);
      m_imageLabel.setScaledContents(true);
      connect(&m_zoomIn, &QPushButton::clicked, [this]{ scaleImage(1.1); });
      connect(&m_zoomOut, &QPushButton::clicked, [this]{ scaleImage(1.0/1.1); });
   }
   void scaleImage(double factor) {
      m_scaleFactor *= factor;
      m_scaleLabel.setText(QStringLiteral("%1%").arg(m_scaleFactor*100, 0, 'f', 1));
      QSize size = m_imageLabel.pixmap()->size() * m_scaleFactor;
      m_imageLabel.resize(size);
   }
};

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   FragTreeViewer viewer;
   QNetworkAccessManager mgr;
   QScopedPointer<QNetworkReply> rsp(
            mgr.get(QNetworkRequest({"http://i.imgur.com/ikwUmUV.jpg"})));
   QObject::connect(rsp.data(), &QNetworkReply::finished, [&]{
      if (rsp->error() == QNetworkReply::NoError)
         viewer.setImage(QImage::fromData(rsp->readAll()));
   });
   viewer.show();
   return a.exec();
}