【问题标题】:How to resize child QLabel (having a QPixmap) with QHBLayout keeping aspect ratio?如何使用保持纵横比的 QHBLayout 调整子 QLabel(具有 QPixmap)的大小?
【发布时间】:2017-09-13 17:59:51
【问题描述】:

我在父 QWidget 内以 this 命名的 QHBLayout 内动态创建一个名为 labelQLabel(有一个 QPixmap),这样 QLabel 图像使用父 this 调整大小,但保持原始图像纵横比。

我现在正在做的事情如下:

QHBoxLayout* layout = new QHBoxLayout(this);
label = new QLabel(str, this); /* This Label is my concern */
label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
layout->addWidget(label);
layout->setAlignment(Qt::AlignCenter);
this->setLayout(layout);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
label->setScaledContents(true);
label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

在网上搜索并按照Qt layouts - Keep widget aspect ratio while resizing 中接受的答案中的建议后,我什至尝试创建自己的MyLabel 类并定义sizeHint()resizeEvent(QResizeEvent* event),如下所示:

QSize MyLabel::sizeHint() const
{
    QSize s = size();
    lastHeight = s.height();
    lastWidth = s.width();
    QSize qs = QLabel::sizeHint();
    float ratio = std::min(((float)qs.width())/lastWidth, ((float)qs.height())/lastHeight);
    s.setWidth(lastWidth*ratio);
    s.setHeight(lastHeight*ratio);
    return s;
}

void MyLabel::resizeEvent(QResizeEvent* event)
{
    QLabel::resizeEvent(event);
    if(lastHeight!=height())
    {
        updateGeometry();
    }
}

label 图像仍会在不保持纵横比的情况下调整大小。

我在这里错过了什么?

任何帮助将不胜感激。 提前致谢。

【问题讨论】:

    标签: image qt resize qlabel


    【解决方案1】:

    尝试使用此处列出的 QLabel 的子类:

    https://stackoverflow.com/a/22618496/999943

    希望对您有所帮助。

    【讨论】:

    • 这个类有效。在比较我定义的MyLabel 和这个AspectRatioPixmapLabel 类时,发现主要的罪魁祸首是使用函数调用作为setScaledContents(true);。必须设置为setScaledContents(false);。所以我提议更新你的有用答案。
    【解决方案2】:

    尝试调整图片大小,而不是 QLabel。例如。通过挂起父小部件的 resizeEvent 并执行以下操作:

    const QPixmap* pixmap = label->pixmap();
    if (pixmap->width() >= newGeometry.width())
    {
        QPixmap scaledPixmap = pixmap->scaledToWidth(newWidth, Qt::SmoothTransformation);
        label->setPixmap(scaledPixmap);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2013-06-26
      • 2012-04-15
      • 1970-01-01
      相关资源
      最近更新 更多