Evgenii Legotckoi
March 30, 2017, 11:47 p.m.

Qt/C++ - Lesson 061. Adding images to the application using the Drag And Drop method from the file manager

Let's write a small application that will allow Drag and Drop to drag and drop images from the file manager into the application itself. In this application, there will be an image preview area and a list of all the images that we put into our application. In this case, when clicking on the image in the list, the image will be placed in the main view area, by which we clicked. In this list, each element will have a preview of the image without text. This preview will be generated using a delegate inherited from QStyledDelegate .

The application will look like this:


Project structure

  • DropEvent.pro - project profile;
  • main.cpp - File with the main function;
  • widget.h - The header file for the application window;
  • widget.cpp - The application source code file;
  • imagedelegate.h - Header file of the list item delegate;
  • Imagedelegate.cpp - File of the source code of the delegate of the list item.

A delegate in this project is required in order to delete the text under the images. The fact is that for displaying thumbnails of images, QListView and QStandardItemModel will be used, which do not have the functionality of displaying icons without text. But you can remove the text using the delegate, completely redefining the appearance of the list item.

I will not bring the source code for the DropEvent.pro and main.cpp files, because there is the default code generated when creating the project.

widget.h

In the window of the application window, we redefine the methods for the Drag and Drop events, and also add objects for the interface and the data model for the images.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5. #include <QPalette>
  6. #include <QDragEnterEvent>
  7. #include <QMimeData>
  8. #include <QDropEvent>
  9. #include <QScrollArea>
  10. #include <QLabel>
  11. #include <QListView>
  12. #include <QGridLayout>
  13. #include <QStandardItemModel>
  14.  
  15. class Widget : public QWidget
  16. {
  17. Q_OBJECT
  18.  
  19. public:
  20. explicit Widget(QWidget *parent = 0);
  21. ~Widget();
  22.  
  23. // Drag event method
  24. virtual void dragEnterEvent(QDragEnterEvent* event) override;
  25. // Method for drop an object with data
  26. virtual void dropEvent(QDropEvent *event) override;
  27.  
  28. private slots:
  29. // Slot for processing clicks on list items
  30. void onImagesListViewClicked(const QModelIndex& index);
  31.  
  32. private:
  33. QScrollArea* m_scrollArea; // Image scrolling area
  34. QLabel* m_imageLabel; // Label for displaying pictures
  35. QListView* m_imagesListView; // List with images
  36. QGridLayout* m_gridLayout; // Grid for the interface
  37. QStandardItemModel* m_imagesModel; // Data Model with Images
  38. };
  39.  
  40. #endif // WIDGET_H

widget.cpp

To form a list with images, QStandardItemModel will be used, and QListView will be used to display the model elements. For customized display of items in the list, the Delegate will be used, because only redefining the appearance display can remove the text. By the way, this text contains the path to the image file, which will be used to create a QPixmap and display the image both in the main view and in the previews. To get the path to the file from the data model, you need to use the data() method, and pass QModellndex and enum Qt::DisplayRole as the arguments, which is the default argument.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. #include <QStandardItem>
  5. #include "imagedelegate.h"
  6.  
  7. Widget::Widget(QWidget *parent) :
  8. QWidget(parent)
  9. {
  10. setAcceptDrops(true); // Allow drop events for data objects
  11. setMinimumWidth(640);
  12. setMinimumHeight(480);
  13.  
  14. /// Configure the interface
  15. m_gridLayout = new QGridLayout(this);
  16. m_imagesListView = new QListView(this);
  17.  
  18. // Create a data model for the image list
  19. m_imagesModel = new QStandardItemModel(m_imagesListView);
  20. m_imagesListView->setModel(m_imagesModel); // Install the model in the view for preview images
  21. m_imagesListView->setFixedWidth(200);
  22.  
  23. // Without a delegate, you can not get rid of the text in the list item and set the display of the preview
  24. m_imagesListView->setItemDelegate(new ImageDelegate(m_imagesModel, m_imagesListView));
  25.  
  26. // Adjust the scrolling area for the current image
  27. m_scrollArea = new QScrollArea(this);
  28. m_scrollArea->setBackgroundRole(QPalette::Dark);
  29. m_imageLabel = new QLabel(this);
  30. m_scrollArea->setWidget(m_imageLabel);
  31. m_gridLayout->addWidget(m_scrollArea, 0, 0);
  32. m_gridLayout->addWidget(m_imagesListView, 0, 1);
  33.  
  34. connect(m_imagesListView, &QListView::clicked, this, &Widget::onImagesListViewClicked);
  35. }
  36.  
  37. Widget::~Widget()
  38. {
  39.  
  40. }
  41.  
  42. void Widget::dragEnterEvent(QDragEnterEvent *event)
  43. {
  44. // You must necessarily accept the data transfer event in the application window area
  45. event->accept();
  46. }
  47.  
  48. void Widget::dropEvent(QDropEvent *event)
  49. {
  50. // When we drop the file into the application area, we take the path to the file from the MIME data
  51. QString filePath = event->mimeData()->urls()[0].toLocalFile();
  52. // Create an image
  53. QPixmap pixmap(filePath);
  54. // We place it in the scrolling area through QLabel
  55. m_imageLabel->setPixmap(pixmap);
  56. m_imageLabel->resize(pixmap.size());
  57.  
  58. // Adding an item to the list
  59. m_imagesModel->appendRow(new QStandardItem(QIcon(pixmap), filePath));
  60. }
  61.  
  62. void Widget::onImagesListViewClicked(const QModelIndex &index)
  63. {
  64. // When we click on an element in the list, we take the path to the file
  65. QPixmap pixmap(m_imagesModel->data(index).toString());
  66. // And install the file in the main view area
  67. m_imageLabel->setPixmap(pixmap);
  68. m_imageLabel->resize(pixmap.size());
  69. }

imagedelegate.h

And here is the delegate himself, whose task it is to display the item in the list. To get the path to the image file, I passed a pointer to the data model, and through QModelIndex in the paint method I get the path to the image.

Another important point is the use of the sizeHint() method. Which adjusts the size of the item in the list. If it does not make a size adjustment, then the element's size will be equal in height to the text line. The preview will look absolutely awful.

  1. #ifndef IMAGEDELEGATE_H
  2. #define IMAGEDELEGATE_H
  3.  
  4. #include <QStyledItemDelegate>
  5. #include <QPainter>
  6. #include <QStyleOptionViewItem>
  7. #include <QModelIndex>
  8. #include <QStandardItemModel>
  9. #include <QPixmap>
  10. #include <QDebug>
  11.  
  12. class ImageDelegate : public QStyledItemDelegate
  13. {
  14. public:
  15. explicit ImageDelegate(QStandardItemModel *model, QObject *parent = nullptr);
  16.  
  17. virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
  18. virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
  19. QStandardItemModel* m_model;
  20. };
  21.  
  22.  
  23. #endif // IMAGEDELEGATE_H

Imagedelegate.cpp

Another important point is the use of QRect from QStyleOptionViewItem. The fact is that it contains not only the height and width of the element, but also its position in x and y in the list. If you do not take into account these coordinates, you can see that all the elements will be drawn in one place. For example, in the upper left corner of the list, if you specify x = 0 and y = 0 when drawing.

  1. #include "imagedelegate.h"
  2.  
  3. ImageDelegate::ImageDelegate(QStandardItemModel *model, QObject *parent) :
  4. QStyledItemDelegate(parent),
  5. m_model(model)
  6. {
  7.  
  8. }
  9.  
  10. void ImageDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
  11. {
  12. // Instead of drawing icons and text, we will draw only one image with small indents of 5 pixels
  13. QPixmap pix(m_model->data(index).toString());
  14. QRect optionRect = option.rect;
  15. painter->drawPixmap(optionRect.x() + 5,
  16. optionRect.y() + 5,
  17. optionRect.width() - 10,
  18. optionRect.height() - 10 ,
  19. pix);
  20. }
  21.  
  22. QSize ImageDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
  23. {
  24. // Correct the size of the display area of the object in the list
  25. QSize result = QStyledItemDelegate::sizeHint(option, index);
  26. result.setHeight(140);
  27. result.setWidth(140);
  28. return QSize(140, 140);
  29. }

Project application with Drag and Drop

Recommended articles on this topic

By article asked0question(s)

4

Do you like it? Share on social networks!

Юрий
  • Jan. 21, 2021, 12:34 a.m.

// Вместо отрисовки иконки и текста будем отрисовывать только одно изображение
// с небольшими отступами в 5 пикселей
QPixmap pix(m_model->data(index).toString());

А можно сразу передовать Qpixmap?

Evgenii Legotckoi
  • July 2, 2021, 5:45 p.m.

Нет, нужно сконвертировать информацию в удобоваримый mime type

Ruslan Polupan
  • Aug. 11, 2022, 1:37 p.m.

Доброго времени суток.
А если нужно и изображение и текст?
Что-то потерялся немного....

// Вместо отрисовки иконки и текста будем отрисовывать только одно изображение
// с небольшими отступами в 5 пикселей
QPixmap pix(m_model->data(index).toString());

Evgenii Legotckoi
  • Aug. 24, 2022, 5:32 p.m.

Добрый день. Посмотрите описание методов drawText у QPainter, он позволит и текст нарисовать

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html