根据宽度

时间:2015-12-15 15:52:53

标签: c++ qt qwidget

我有一个包含图像的QLabel。我需要确保图像总是占用QLabel宽度的100%,但保留纵横比同样重要。这意味着我还需要增加QLabel高度以使图像适合。就像在这张图片上一样,高度必须合适:

image description

我Qt设计师我认为没有办法指定首选宽高比,所以我只是试图覆盖resize事件并尝试在调整大小时强制正确的高度:

void QPictureLabel::resizeEvent(QResizeEvent *event)
{
    qDebug()<<"Resized.";
    // Current image width in pixels
    float pw = myPixmap.width();
    // current label width in pixels
    float my_width = width();
    // ratio of label and image width can decide the new required label height
    float new_h = (my_width/pw)*myPixmap.height();
    // This is an attempt to prevent endless loop... didn't work out
    if(new_h!=height()) {
        // Force new height (that works)
        resize(my_width, new_h);
        // Tell the layout to move other elements (that doesn't work at all!)
        updateGeometry();
    }
}

在添加updateGeometry电话之前,它看起来像这样:

image description

正如您所看到的(我用红框突出显示),标签确实根据需要进行了扩展。但其他小部件并不关心这一点。

我添加了updateGeometry调用,但由于某种原因,结果是无限循环。我需要正确的方法告知布局QLabel需要更多空间

1 个答案:

答案 0 :(得分:-1)

  

但由于某种原因结果是无限循环

这是有关resizeEvent()的文档,阅读文档。 Shf的解决方案应该适合你。