Displaying a picture with PictureWidget
This widget will be called to display a picture at its full size. We also add some buttons to go to the previous/next picture or delete the current one.
Let's start to analyze the PictureWidget.ui form, here is the design view:
Here are the details:
- backButton: This object requests to display the gallery
- deleteButton: This object removes the picture from the album
- nameLabel: This object displays the picture name
- nextButton: This object selects the next picture in the album
- previousButton: This object selects the previous picture in the album
- pictureLabel: This object displays the picture
We can now take a look at the header PictureWidget.h:
#include <QWidget> #include <QItemSelection> namespace Ui { class PictureWidget; } class PictureModel; class QItemSelectionModel; class ThumbnailProxyModel; class PictureWidget : public QWidget { Q_OBJECT public: explicit PictureWidget(QWidget *parent = 0); ~PictureWidget(); void setModel(ThumbnailProxyModel* model); void setSelectionModel(QItemSelectionModel* selectionModel); signals: void backToGallery(); protected: void resizeEvent(QResizeEvent* event) override; private slots: void deletePicture(); void loadPicture(const QItemSelection& selected); private: void updatePicturePixmap(); private: Ui::PictureWidget* ui; ThumbnailProxyModel* mModel; QItemSelectionModel* mSelectionModel; QPixmap mPixmap; };
No surprises here, we have the ThumbnailProxyModel* and QItemSelectionModel* setters in the PictureWidget class. The signal backToGallery() is triggered when the user clicks on the backButton object. It will be handled by MainWindow to display again the gallery. We override resizeEvent() to ensure that we always use all the visible area to display the picture. The deletePicture()slot will process the deletion when the user clicks on the corresponding button. The loadPicture()function will be called to update the UI with the specified picture. Finally, updatePicturePixmap() is a helper function to display the picture according to the current widget size.
This widget is really similar to the others. As a result, we will not put the full implementation code of PictureWidget.cpp here. You can check the full source code example if needed.
Let's see how this widget is able to always display the picture at its full size in PictureWidget.cpp:
void PictureWidget::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); updatePicturePixmap(); } void PictureWidget::updatePicturePixmap() { if (mPixmap.isNull()) { return; } ui->pictureLabel->setPixmap(mPixmap.scaled(ui->pictureLabel->size(), Qt::KeepAspectRatio)); }
So, every time the widget is resized, we call updatePicturePixmap(). The mPixmap variable is the full-size picture from PictureModel. This function will scale the picture to the pictureLabel size, keeping the aspect ratio. You can freely resize the window and enjoy your picture with the biggest possible size.