QGraphicsView strange resize behaviour
-
Hi,
complete Qt newbie here experiencing some strange behaviour on one of my projects.
I'm trying to display an image in a QGraphicsView, everything works fine until I try to implement an resize event for scaling and call the installEventFilter method. Then my picture won't be displayed when first loaded but instead after the first resize gets triggered, everything from then works flawlessly and I don't get behind the problem.Here ia my code from my main class:
void main::on_openFileButton_clicked() { try{ fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "/", tr("Image Files (*.png *.jpg *.bmp)")); } catch (std::exception & e) { QMessageBox msgBox; msgBox.setText("An error occured please try again!"); msgBox.exec(); } if(fileName == NULL){ QMessageBox msgBox; msgBox.setText("Please select a picture file to open"); msgBox.exec(); } else { scene = new Scene(this); if(scene->loadImage(&fileName)) { //let QGraphicsView display the Scene ui->drawBoard->setScene(scene); ui->drawBoard->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); //Align top center ui->drawBoard->setAlignment(Qt::AlignCenter | Qt::AlignTop); //set Grapicsview size to fit the image ui->drawBoard->fitInView(scene->getImage().rect(), Qt::KeepAspectRatio); //set Scene outline to image size ui->drawBoard->setSceneRect(scene->getImage().rect()); this->installEventFilter(this); } } }
Here is loadImage method from my scene class which is derived from QScene:
bool Scene::loadImage(QString *fileName) { bool retval = false; //Create QImage and load file image = QImage(*fileName); //Create pixmap and load QImage, keep Aspect ratio & do some pixel smoothing pixmap = (QPixmap::fromImage(image).scaled(image.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); //add Pixmap to scenes if (this->addPixmap(pixmap) != NULL) retval = true; return retval; }
And my eventHandler:
bool main::eventFilter(QObject *obj, QEvent *event) { //Resize Graphicsview on first startup if (event->type() == QEvent::Show){ if(scene != NULL) ui->drawBoard->fitInView(scene->getImage().rect(), Qt::KeepAspectRatio); } //Resize GraphicsView when main window gets resized if (event->type() == QEvent::Resize){ if(scene != NULL) ui->drawBoard->fitInView(scene->getImage().rect(), Qt::KeepAspectRatio); } return true; }
-
Hi,
Returning true from your custom filter means that the event has been handled and no further actions needs to be done which is not the case here.
You should rather use
return QObject::eventFilter(obj, event);
On a side note, theres no need to use a pointer to a QString in your
loadImage
method. Just use a const reference. QString is an implicitly shared class so passing it as const reference doesn't trigger any copy and it also avoid an unneeded dereferencing.