IscanderChe29 июня 2019 г. 12:09
Как отобразить QPainter в кастомном виджете с фиксированными размерами
Разрабатываю виджет для просмотра изображений в миниатюре.
Что получилось: показать изображение в рамке (см. прицеп). Но беда в том, что при ресайзе основного виджета виджеты с картинками тоже ресайзятся (опять же см. прицеп), чего делать уже не надо. Как решить эту задачу, помогите, плиз.
// widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); }; #endif // WIDGET_H // widget.cpp #include "widget.h" #include "paintwidget.h" #include <QVBoxLayout> #include <QHBoxLayout> Widget::Widget(QWidget *parent) : QWidget(parent) { PaintWidget* paintWidget1 = new PaintWidget(parent); PaintWidget* paintWidget2 = new PaintWidget(parent); QVBoxLayout* layoutV = new QVBoxLayout; layoutV->addWidget(paintWidget1); layoutV->addWidget(paintWidget2); setLayout(layoutV); } Widget::~Widget() { } // paintwidget.h #ifndef PAINTWIDGET_H #define PAINTWIDGET_H #include <QWidget> class PaintWidget : public QWidget { Q_OBJECT public: explicit PaintWidget(QWidget *parent = 0); protected: void paintEvent(QPaintEvent*); private: int rectPhotoX; int rectPhotoY; int rectPhotoWidth; int rectPhotoHeight; }; #endif // PAINTWIDGET_H // paintwidget.cpp #include "paintwidget.h" #include <QPainter> PaintWidget::PaintWidget(QWidget *parent) : QWidget(parent) { } void PaintWidget::paintEvent(QPaintEvent*) { QPainter painter(this); rectPhotoX = 0; rectPhotoY = 0; rectPhotoWidth = 110; rectPhotoHeight = 110; int rectPhotoRadius = 5; QRect rect(rectPhotoX, rectPhotoY, rectPhotoWidth, rectPhotoHeight); painter.setClipRect(rect); QBrush brush(Qt::white, Qt::SolidPattern); painter.fillRect(rect, brush); QImage img(":/images/DSC_0024.jpg"); painter.setRenderHint(QPainter::Antialiasing, true); painter.setBrush(QBrush(Qt::white)); painter.setPen(QPen(Qt::black, 1, Qt::DotLine)); QRect rectPhoto(rectPhotoX, rectPhotoY, rectPhotoWidth, rectPhotoHeight); painter.drawRoundedRect(rectPhoto, rectPhotoRadius, rectPhotoRadius); int minimumOffset = 10; int maximumWidthPhotoView = rectPhotoWidth - minimumOffset * 2; int maximumHeightPhotoView = rectPhotoHeight - minimumOffset * 2; int coefficientWidth = img.width() / maximumWidthPhotoView; int coefficientHeight = img.height() / maximumHeightPhotoView; int coefficient = 0; if(coefficientWidth > coefficientHeight) coefficient = coefficientWidth; else coefficient = coefficientHeight; int realWidthPhotoView = img.width() / coefficient; int realHeightPhotoView = img.height() / coefficient; int offsetX = (rectPhotoWidth - realWidthPhotoView) / 2; int offsetY = (rectPhotoHeight - realHeightPhotoView) / 2; int photoViewX = rectPhotoX + offsetX; int photoViewY = rectPhotoY + offsetY; QImage img2 = img.scaled(realWidthPhotoView, realHeightPhotoView); painter.drawImage(photoViewX, photoViewY, img2); }
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.Вам это нравится? Поделитесь в социальных сетях!
Комментарии
Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь
Пожалуйста, авторизуйтесь или зарегистрируйтесь
d
- dsfs
- 26 апреля 2024 г. 4:56
C++ - Тест 004. Указатели, Массивы и Циклы
- Результат:80баллов,
- Очки рейтинга4
d
- dsfs
- 26 апреля 2024 г. 4:35
C++ - Тест 001. Первая программа и типы данных
- Результат:73баллов,
- Очки рейтинга1
Последние комментарии
Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5 февраля 2024 г. 1:50
EVA25 декабря 2023 г. 10:30
Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Сейчас обсуждают на форуме
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi2 мая 2024 г. 14:07
IscanderChe30 апреля 2024 г. 4:22
Павел Дорофеев14 апреля 2024 г. 2:35
Удалось решить так: