I am working with the Designer inside the Qt Creator and have a QMainWindow
with a QLabel
in it. Because the program loads pictures and displays them inside the label i want that the label resizes with a ratio of 1.25 inside setted boundaries when expanding or shrinking the QMainWindow
. The label should resize INDEPENDENT, again INDEPENDENT from its content.
What i want:
Therefor i...
QLabel
(called imageLabel
) inside the centralWidget
of the QMainWindow
centralWidget
's layout to grid layout ( QGridLayout
) QLabel
:
Element structure:
This doesn't work because i can not set an initial size in the 'geometry' section. The label does not scale with fixed ratio although it respects minimum and maximum values.
Following that answer i set an initial pixmap:
QPixmap p;
ui->imageLabel->setPixmap(p.scaled(640, 512, Qt::KeepAspectRatio));
Which didn't change anything.
I also applied the other answer 's class and promoted it to the widget:
That didn't change anything too.
I then combined the 2. and 3. approach and set an initial pixmap which...
...didn't change anything.
Here is what it does for the approaches 1. - 4.:
Adding the label of 4. approach into a widget:
Well the label doesn't resize at all:
So, how can get the label to have an initial size of 640 x 512 and scale with fixed ratio between 1280 x 1024 and 320 x 256 ?
A possible solution is to install an eventFilter to the centralwidget so doing the required calculation is set the size.
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->centralWidget->installEventFilter(this);
ui->imageLabel->setPixmap(QPixmap(":/image.png"));
ui->imageLabel->setScaledContents(true);
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
const float ratio = 1.25;
if(watched == ui->centralWidget && event->type() == QEvent::Resize
&& ui->centralWidget->width() > 0
&& ui->centralWidget->height() > 0){
float central_ratio = 1.0*ui->centralWidget->width()/ui->centralWidget->height(); QSize s;
if(central_ratio > ratio){
s = QSize(ratio*ui->centralWidget->height(), ui->centralWidget->height());
}
else{
s = QSize(ui->centralWidget->width(), ui->centralWidget->width()/ratio);
}
ui->imageLabel->resize(s);
}
return QMainWindow::eventFilter(watched, event);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.