Home > Mobile >  Qt, Unable to get QLabel dimmensions to correctly scale a QPixmap to its fully fit QLabel
Qt, Unable to get QLabel dimmensions to correctly scale a QPixmap to its fully fit QLabel

Time:12-10

So I'm trying to scale an Image to fully fit a label from top to bottom. The problem is the outputs from the labels width, and height is not pixel values so I'm not sure how to correctly go about this. Here's my code.

void MainWindow::drawPixmap()
{
    int labelWidth = ui->picLabel->width();
    int labelHeight = ui->picLabel->height();

    if(labelWidth <= labelHeight){
        pixMap = this->pixMap.scaledToWidth(labelWidth);
        ui->picLabel->setPixmap(pixMap);
    }
    else{
        pixMap = this->pixMap.scaledToHeight(labelHeight);
        ui->picLabel->setPixmap(pixMap);
    }
}

Here's a visual of my problem, the black box is a border around the label box. I'm trying to get the image in the center to have its top and bottom touch the black box on respective sides.

enter image description here

Thanks for any help!

CodePudding user response:

The problem could be when you calling this function. If you have called this function prior to making the label visible, then the size of the label could be incorrect after the label becomes visible. Also, think about what happens when the label resize (if ever). You will still have to update the size of pixmap. If your label is never going to change size, try calling it after the label has become visible. Alternatively, try setting QLabel::setScaledContents(true)

If both the above doesn't work, try installing an eventFilter on the label to get the label's size change event, in there, you could do your above code

MainWindow::MainWindow()
{
     ....
     ui->picLabel->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
    bool res = Base::eventFilter(object, event);
    if (object == ui->picLabel && event->type() == QEvent::Resize)
    {
        int labelWidth = ui->picLabel->width();
        int labelHeight = ui->picLabel->height();

        if(labelWidth <= labelHeight){
            pixMap = this->pixMap.scaledToWidth(labelWidth);
            ui->picLabel->setPixmap(pixMap);
        }
        else{
            pixMap = this->pixMap.scaledToHeight(labelHeight);
            ui->picLabel->setPixmap(pixMap);
        }
    }
    return res;
}
  • Related